sometimes rspec is easier and faster than cucumber

I’ve been writing a lot of cucumber scenarios for this project I’m working on. I like the syntax, and I like how easy it is to automate tests against the rails stack. I just ran into a simple case where rspec is much easier, quicker to write and quicker to run.

I’m using Authlogic and CanCan to authenticate and authorize requests to my application. I started doing the silly thing of double checking my controller authentication in cucumber.

This makes some sort of sense, from the point of view that it’s loading an entire Rails stack. Unfortunately it would be the source of a hell of a lot of repetition in my tests, as well as unnecessary slowness as the project increases in size. I realized this morning that actually, this can be written as a unit test for my controllers.

1
2
3
4
def authenticate_request(*args)
  self.send(args.shift, args.shift, args.shift)
  response.should redirect_to(login_url)
end

Now I can do this:

1
2
3
4
5
6
7
8
it "authenticates for its actions" do
    authenticate_request(:get, :index)
    authenticate_request(:get, :new)
    authenticate_request(:get, :show, :id => mock_model(MyModel))
    authenticate_request(:post, :create)
    authenticate_request(:delete, :destroy, :id => mock_model(MyModel))
    authenticate_request(:put, :update, :id => mock_model(MyModel))
end

I should actually abstract that it its own method, so I can quickly unit test other controllers without repetition.

This isn’t to say that I couldn’t refactor this better in cucumber. I think I may move most of my authentication/authorization testing into unit tests, however, based on the difference in complexity.

Edit: yeah, so this was covered in a Railscast almost a year ago. Still, its a big revelation to me that this should be in my specs rather than my features.

Comments are closed.