Test Views in ASP.NET MVC2 (ala RSpec) - asp.net-mvc

I am really missing heavily the ability to test Views independently of controllers. The way RSpec does it.
What I want to do is to perform assertions on the rendered view (where no controller is involved!). In order to do so I should provide required Model, ViewData and maybe some details from HttpContextBase (when will we get rid of HttpContext!).
So far I have not found anything that allows doing it. Also it might heavily depend on the ViewEngine being used.
List of things that views might contain are:
Partial views (may be nested deeply).
Master pages (or similar in other view engines).
Html helpers generating links and other elements.
Generally almost anything in a range of common sense :) .
Also please note that I am not talking about client-side testing and thus Selenium is just not related to it at all. It is just plain .NET testing.
So are there any options to actually do the testing of views?
Thanks,
Dmitriy.

The main issue with testing full views is that the asp.net view engine calls Response.Write in the supplied context / and not on the supplied writer.
The above is not the case for testing partial views, so for those you can use this solution:
http://www.brightmix.com/blog/renderpartial-to-string-in-asp-net-mvc/
There are other view engines that do allow you to test the view i.e. Spark.
ps. the concept in asp.net mvc is that you should be able to test the view by using the ViewEngine, but as I understand the asp.net mvc team didn't work around the existing asp.net engine restrictions to be able to do so for their view engine.

You may want to check out the UI Test Helpers that Eric Hexter and the guys with MVCContrib are working on. I haven't had a chance to look at it in depth, but it may help you. I found this link that shows some of the syntax: http://codepaste.net/cw8ie4
I would be interested to know what you find out as I will be doing this pretty soon also.

Interested to know if you find anything for .Net that does this. Our current app is WPF, but we are stuck with trusting Cucumber to touch our Views in all our Features... so yeah, that sucks. Hope you find something and update us.

Related

Changing the View Engine in Asp.NET MVC

I am trying to learn ASP.NET MVC by porting my current app written in ASP.NET Webforms to MVC. For starters, I am planning to use the Default View Engine (WebFormsViewEngine) as most tutorials/examples and the book I have use that as the default.
However, I know for sure that I do not want to use WebformViewEngine in the future and once I have a grasp of MVC, I would like to switch to a different ViewEngine (Spark seems to be interesting)
Would this be a simple change or would it take a lot of effort in terms of coding new views? What I basically want to know is which would involve more effort? Learning an alternate ViewEngine now or switching later?
OK - firstly you've got a decent sized investment in WebForms I'm assuming, and by virtue of that, you'll have a fair amount of user controls on existing forms etc. I'm sure you already know that this in itself is going to be the most work in the process, and has nothing to do with which view engine you choose because even the WebForms MVC view engine doesn't support user controls directly. This part of the work will still need to be done regardless...
Secondly, you probably are looking for a view engine that can take most of your other view built in logic and code (i.e not user controls), and by that I mean the stuff between the bee-stings ( <%= blah %> ).
Obviously the WebForms view engine does support this same syntax, but you also say that you specifically don't want to use the default WebForms view engine. Well you'll be happy to know that Spark also supports the <%= blah %> syntax, and this has been done specifically to support migrations like this.
Your best bet before deciding would be to watch this recent video here, and see how Louis goes through the simple WebForms-based MVC solution and it keeps running correctly even though the code still contains <%= blah %> syntax.
This support makes it much easier to transition and when you're ready you can then start moving your code to the more recommended way of using ${blah} syntax instead. But this can be done at your own pace whilst the overall functionality still works.
Hope that helps,
All the best,
Rob G
Looks like you can have a mixed bag of view engines in your application... link
Also check out this post from Phil Haack that shows using partials using different view engines to render on the same page.
This would allow you to simply switch over to the new syntax and not need to rewrite all of your existing views.
It should be as simple as calling
SparkEngineStarter.RegisterViewEngine(ViewEngines.Engines);
SparkEngineStarter should be a class in the Mvc part of Spark.
The documentation of spark is actually pretty good. Check out the section on getting it to run in ASP.NET MVC

Does ASP.NET MVC require you to use master pages?

My group is working on a new web application and is considering using MVC. However, there are members who would rather include pages than use master pages. Is this possible to do in ASP.NET MVC? In the small amount of time that I've poked around with MVC I have not yet been able to figure out how one might accomplish that.
Why the preference?
Having used both in the past, Master Pages are much easier to use. You just have to get over the (very small) learning curve.
ASP.NET MVC doesn't force you to do either one though...
If you like the Include method, then you would probably feel most comfortable using Partial Views to provide the same functionality. You would just add the Partial Views to each page instead of including another page.
No. It does not force you in any way.
You should really avoid server-side includes with anything newer than classic ASP. They're more difficult to debug, IIS has a hard time finding correct line numbers when there's a problem, etc. Also, I haven't looked at the order in which SSIs are processed in the request pipeline - they may not work at all with ASP.NET.
If you're moving into MVC, use RenderPartial() or RenderAction() instead. These perform essentially the same function as a server-side include, but are more inline with the spirit of the framework and provide some additional benefits, like passing models without having to declare a global variable (which should also be avoided, and I'm not sure if it is even possible under .NET scope rules).
And, no, master pages are not required, but you really should use them. Using includes to build your page layout works, but only if you don't and won't need to radically change the layout of your site at any point in the future. I'm in that boat now with a 350k line classic ASP app which used very nicely structured code and #includes to create the page layout. That was the best solution available at the time, but it's causing me a lot of headaches now (10+ years later).
With a master page you can move your ContentPlaceHolder blocks anywhere you want, whereas with #includes the final page really determines the format by the order in which the includes are placed. This also makes it pretty straightforward to create a mobile version of your site - you can create a mobile-specific master page and use the same content views.
Its a matter of choice,but for consistent look and feel across the web application, master pages give you just that. You have to take the team through the learning curve of good master page design, not only would it be useful for the current project at hand but also future projects. Good luck!
I would rather opt to go for Master pages due to the ease of use and built in support in MVC for this.
If you want to know more about it check out this tutorial: Creating Page Layouts with View Master Pages.
Grz, Kris.

Asp.Net MVC Identify Site via Url

I have an application that will support multiple sites. The site will be determined based on the url.
For example
http://myapp/site/abc123/...
and
http://myapp/site/xyz123/...
The site code will drive a lot of the functionality for example themes, available modules, etc...
Questions:
1-)I need to validate the site code is valid and if it isn't, it should direct the user to an info page. I was looking at using IRouteConstraint, is this appropriate? Are there other/better options?
2-)Any gotchas with this approach (using url to identify site)? Is there are better approach?
Solution
I ended up creating a Custom ActionFilter and check the sitecode in the OnActionExecuting event. That seems to work well and fit better than the IRouteConstraint.
The system I have implemented uses Urls to identify unique page content within a single site and the routing process is pretty straightforward. That being said, you may want to consider making use of Areas in your MVC application. With Areas you can have multiple sections to your website that all have their own MVC structure which can run semi-independently.
Essentially, you will have one base routing definition that lays out some defaults and then the rest of the "sites" will define their own routes pointing to controllers and views in a separate location. It's pretty easy to set up, you'll just need to make sure you're using version 2.0 of ASP.NET MVC. Here's a decent looking tutorial on ASP.NET MVC Areas and Routes. In the current model which MVC 2.0 supports you'll have a single Web project for each area, but that is not necessarily a requirement. Phil Haacked has some code for ASP.NET MVC Single Project Areas if you're looking for another example of the technique, although you, personally, will probably benefit more from the first article.
So long as you define good routes that have clear and measurable constraints, you shouldn't have too much trouble laying out the website you've described.
I ended up creating a Custom ActionFilter and check the sitecode in the OnActionExecuting event. That seems to work well and fit better than the IRouteConstraint.

Using Code-Behind with ASP.NET MVC Views

Is it considered a bad practice to use code-behind with ASP.NET MVC Views? Got into a bit of a debate about this with my colleagues today and I was wondering the community's thoughts.
Obviously, this isn't an option when using another MVC like Rails, which makes me think it's relied on more as a crutch for those accustom to working with traditional ASP.NET Web Forms applications.
I would say that it's a bad practice to use code-behinds with ASP.NET MVC. MVC allows separation of concern where presentation logic (in Views) are separated from application logic (in Controllers). Using code-behinds will mix presentation logic and application logic inside the code-behinds, whereby defeating some of the benefits of MVC.
Certainly the authors of ASP.NET MVC In Action advise against it, and I agree. It isn't necessary, so why do it? In the early betas a code-behind file was included, but this was removed at RTM (or shortly before).
Typically, it simply encourages you to do more non-view work than you should in the view, as it is out of sight / out of mind.
I used code-behind extensively on my first ASP.NET MVC (Preview 3!) project - primarily for doing stuff like casting ViewData["foo"] into strongly-typed data objects, gathering view data into IEnumerables so I could loop across it, that kind of thing.
With the introduction of strongly-typed views, and pragmatic use of the (horrifically-named) Model-View-ViewModel pattern, I haven't missed code-behind at all since it was removed from the project framework just before the final release.
I now strongly feel that whatever processing you're doing in your view's code-behind, you are far better off modelling the result of that processing in your ViewModel, allowing the controller to perform the actual processing, and keep the view as simple and lightweight as you can. That'll let you test the processing logic, it makes the views easier to modify, and creates - I think - a much more elegant separation between transforming your data for display, and actually displaying it.
Yes the codebehind has long been the secret hiding place of business logic which as we all know should not be at the View level.
Code behind has been removed to stop naughty developers from being tempted.
I would recommend avoiding the codebehind in an MVC app at all costs. Using the code behind negates some of the values you get by using the MVC Framework such as separation of concerns, etc. You want to have your data access, business rules, type conversion and that sort of thing applied in the Model. If you find you need to convert your data types like Dylan mentioned, you may want to make ViewModels. The ViewModel would basically be the data from the actual Model you would like to display, in the format you wish to display it in.
Its probably best to avoid putting anything in the code behind when using MVC.
I would be interested to hear which part was being debated about, to go in the codebehind?
If you new to Asp.Net MVC, I really recommend spending some time going through the Nerd dinner example. There's a free EBook and source available here http://nerddinner.codeplex.com/.
Creating the simple demo from scratch is a great way to learn.
After doing this, it may shed some light on where the code you have in the codebehind, could alternatively go.
Note: If you do follow the EBook, grab the latest site.css file from codeplex, otherwise the virtual earth maps won't be aligned properly.
HTH
Ralph
It should be noted that "Code Behind" is a feature of the Web Forms view engine. It really has nothing to do with ASP.NET MVC itself.
For example, the Razor view engine in MVC3 does not even support it.
I would answer your question this way: If you cannot switch view engines without rewriting your controllers (or even your models) then you are not using the MVC pattern correctly.
Probably most of what you are doing in the .aspx.cs file should really be done before the model (or View Model) gets passed to the view. That said, in projects that I have migrated from ASP.NET Web Forms to ASP.NET MVC, I left a lot of the Code Behind in place. For example, I find it cleaner and more pleasing to use a Repeater control than to try to use a 'for' loop in Web Forms. I am still just iterating over View Model data after all. So why not? Separation of concerns is preserved (perhaps to a greater degree in fact).
I mean, why should "best practice" for Web Forms suddenly be the wrong way to do a Web Forms View? As a simple example, consider a Repeater that assigns a different CSS class to every second row of a table. Why should my controller (or even my model) care? Trying to put this kind of logic inline in Web Forms quickly devolves into tag soup and complete spaghetti. Now imagine something more complicated.
I have left Master pages in place that build the menus in the code behind. Again, all data comes from the View Model. I do not see why using GridView or other controls in this way should be a problem either.
I usually disabled ViewState in Web Forms anyway and did the data binding in "Init". Still, there would often be a small ViewState that I could not get rid of. I put some code in "Render" that moves this to after the form (it defaults to before). When moving to MVC, I sometimes left this code in. So, I have ASP.MVC sites that do indeed use Code Behind. I am just careful that it code that is specific to the view.
On new projects, I generally have found less of a need for Code Behind on most pages. Thankfully, view engines like Razor have made mixing code and mark-up in-line a lot less painful to write, read, and maintain.

What is the best/cleanest way to implement A-B testing in asp.net mvc?

What is the best and cleanest way to implement A-B testing in asp.net mvc? That is, when we make new changes to an asp.net mvc web site, we want to test the new html/css/js with a certain subset of visitors (defined on cookie, login id, etc) and then analyze some metrics (page response time, number of pages visited, $$$ in sales, etc) afterwards to measure the level of success of the changes.
I am looking for a clean way to implement a way of choosing what view (html/css/js, etc...) to render using asp.net mvc.
Check out FairlyCertain (http://www.fairtutor.com/fairlycertain/) when you get a chance. It's a .NET A/B library that you can pretty much just drop into your project and start writing tests.
Unlike the Javascript libraries from Google and VisualWebsiteOptimizer, everything happens on the server so you don't suffer any performance, user experience or SEO issues. I've been using it in my stuff for a while now and it works quite well.
There is an A/B testing framework specifically for ASP.NET MVC. This is an open source software I wrote myself when, just like you, didn't find a free tool which works nicely with ASP.NET MVC and doesn't require much setup.
Google Content Experiments? It's a Javascript-based solution that doesn't require anything from your backend.
You include Google's Javascript on your page
The script randomly substitutes elements on your page as defined by your A/B test
Google's site shows you a nice breakdown of the results...
If you are using the spark view engine, you could probably do it with a variation of the theme filter (http://sparkviewengine.com/documentation/viewlocations#Extendingfilepatternswithdescriptorfilters). For each new visitor to the site, determine if you want them to see the existing or new version of the site and set a cookie. Wire up a descriptor filter that looks for the presence of the cookie and modify the view location to look in the folder containing the modified views. If an alternative view exists, the Spark engine will automatically render it in place of the "normal" view, otherwise it will render the normal view.
If you are using the normal WFVE, then the simplest way to manage this would be to define a folder under Views where your view alternatives live. When you want to provide an alternative view, you place it in a location that matches its position within the normal Views folder but rooted at the alternatives folder e.g. to provide an alternative to Views/Users/login.aspx place your new view at Views/Alternative/Users/login.aspx.
With a convention in place for locating your alternative views, you can extend the WebFormViewEngine and overload CreatePartialView / CreateView to inspect some aspect of the ControllerContext to determine whether to render the default or overloaded view and alter the path as appropriate e.g. changing .../Views/Users/login.aspx to .../Views/Alternative/Users/login.aspx.
I suggest you use Display Modes to achieve A/B testing.
But Display Modes just support simple problems by default.
If you already implement Display Modes in some other scenario. You can consider DisplayModeMatrix (just google it). It helps you use Display Modes more efficiency.
https://www.nuget.org/packages/DisplayModeMatrix/
Wth Display Modes you can simply delete/rename views after A/B testing to clean up your project.
I think there isn't a ready to use solution for this and you will have to improvise.
Try to override your current functionality in well defined points without breaking it. Explicitly draw a border where your regular code and A-B testing code lives.
Inversion of control principle might help a lot here too (i.e. - controller factory could provide derived controller instead of original one). For views&partialviews - you could change viewengine so it would try to look for 'MyPartialViewAB.ascx' instead of 'MyPartialView.ascx'.
And it might be a good idea to take a look what performance counters are (in case you haven't).

Resources