So, if you’ve tried RSpec, you know it let’s you write test code that’s easy to understand. There are other reasons for BDD, but that is probably the first one you’ll notice. Describe this, it should do that, this should not have five of those, etc etc. It’s great for less assertive people like myself.
Occasionally, you’ll run into situations that are not easily described with the stock RSpec API. The RSpec guys have done a fantastic job putting together an API that is easy to manipulate, so don’t be afraid to do that!
Let’s look at an example:
1 2 3 4 5 6 7 8 9 |
describe TicketsController, "with unauthenticated visitor" do it "should require login to access /index" do get 'index' # This is the line I'll be picking on. response.should redirect_to( :controller => 'account', :action => 'login' ) end end |
Pretty basic, right? But here’s the part that bugs me: it “should require login to access /index” vs. response.should redirect_to( :controller => ‘account’, :action => ‘login’ ).
The expectation I’ve described in english is not the same as the expectation I’ve described in code. Redirecting to a login page is a function of the before_filter handling your app’s security, not of the TicketsController itself.
In english, my expectation is pretty clear: ‘it should require login’. So let’s make the code match.
1 2 3 4 5 6 7 8 9 |
describe TicketsController, "with unauthenticated visitor" do it "should require login to access /index" do get 'index' # Doesn't this make a lot more sense?? response.should require_login end end |
Turns out, this is shockingly easy to accomplish:
1 2 3 4 5 6 7 |
# Add this to your spec_helper.rb or another required file module Spec::Rails::Matchers def require_login RedirectTo.new(request, { :controller => 'account', :action => 'login' }) end end |
And there you go. Requiring a login is now an expectation on the same level as all others. It’s really very cool!
Additionally, this ALMOST gets us the negative expectation ( “response.should_not require_login” ). There’s a very minor tweak needed to get that working, but that’s an exercise I’ll leave to you.
If you don’t want to figure it out, I can be bribed with gift cards to Caffe Ladro for as little as $5. =)
Leave a Reply