Question

I have a specification written in MSpec that checks whether MVC controller action has been marked with HttpPost attribute:

[Subject(typeof(AccountController))]
public class when_user_logs_in : account_controller_spec
{
    It can_only_submit_form_via_post = () => {
        // some logic to check for HttpPost attribute
        };
}

I am not sure this fits in with how MSpec is meant to be used. Is there a convention for how attribute usage to be checked? If not, is there a better way to name such a specification?

Was it helpful?

Solution

Think about the action that would need to be performed to check wether the system shows the intended behavior. How would you try to ensure that "only submitting via POST" is possible? You might come to the conclusion that you actually need to implement an integration test using WatiN or Selenium and assert that an error page (405, method not allowed) is displayed on non-POST request method.

For a quick'n dirty test you could check the attributes attached to the AccountController's submit method. Following is a Notepad implementation as it's well past midnight where I live:

[Subject(typeof(AccountController))]
public class when_user_logs_in : account_controller_spec
{
    static object Attribute;

    Because of = () => {
      Attribute = typeof(AccountController)
        .GetMethod("Submit")
        .GetCustomAttributes()
        .FirstOrDefault(x => x.Name.Contains = "HttpPost");
    };

    It can_only_submit_form_via_post = () => {
        Attribute.ShouldNotBeNull();
        };
}

As you can see, the specification doesn't really descibe the system's behavior. None of your production code will ever evaluate the statement in the Because delegate. It provides no real value, not for you, and not for your customer. That's why I suggested to use WatiN or something similar to assert on the runtime behavior and not just some attribute slapped onto a method.

I certainly wouldn't test every POST-related controller action manually as that's too much repeated work. Is there a way to find a convention for methods that would require [HttpPost]?

I remember implementing a convention for one of my older FubuMVC projects where we had the convention that all controller actions that return object (method signature) would automatically be limited to POST. The code was actually pretty concise, perhaps an MVC action filter can do the same for you.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top