2

How do you render a view as a string from a controller in MVC 2?

In MVC 1, I used CaptureActionHtml. I'm having the same problem with it as a similar question, but is there a way to do this without Rhink.Mocks?

Community
  • 1
  • 1
user202448
  • 2,552
  • 5
  • 22
  • 25
  • IMHO: You shouldn't. You should do this in an `ActionResult`, not in a `Controller`. What are you trying to do? – Craig Stuntz Apr 30 '10 at 17:22
  • What's the difference? Isn't an ActionResult in the Controller? I'm trying to use the view as template for an email. – user202448 Apr 30 '10 at 17:45
  • 1
    No, Controllers and ActionResults are two different types. Controllers *instantiate* ActionResults; Controllers don't *implement* ActionResults Controllers shouldn't know about HTML at all. Here's the general idea: http://www.aboutcode.net/2009/01/19/EmailActionResultInASPNETMVC.aspx – Craig Stuntz Apr 30 '10 at 21:38

1 Answers1

0

I've found Steve Sanderson's Integration Testing framework to work out very well for this.

Perusing one of the code samples from his own blog post gives you some idea of the capabilities of the framework, the assertions that you can perform against its output, etc:

[Test]
public void Root_Url_Renders_Index_View()
{
    appHost.SimulateBrowsingSession(browsingSession => {
        // Request the root URL
        RequestResult result = browsingSession.ProcessRequest("/");

        // You can make assertions about the ActionResult...
        var viewResult = (ViewResult) result.ActionExecutedContext.Result;
        Assert.AreEqual("Index", viewResult.ViewName);
        Assert.AreEqual("Welcome to ASP.NET MVC!", viewResult.ViewData["Message"]);

        // ... or you can make assertions about the rendered HTML
        Assert.IsTrue(result.ResponseText.Contains("<!DOCTYPE html"));
    });
}