Easy Stubbing in Rails Functional Tests
I discovered a simple, concise approach for stubbing models inside Ruby on Rails controller functional tests. It relies on David Chelimsky’s excellent Stubble gem. It’s a shame it took me 5 months to discover it, even though I sat in on his RailsConf presentation in May, “Don’t Mock Yourself Out.” (doh!). First the why…
The key goal of your functional tests should be isolating what controllers are expected to do. Don’t let pseudo unit tests leak into this realm. Don’t waste your time writing controller tests in which a post containing specific attributes fails because of a validation rule on the instance. Instead focus on what the controller should do if the post resulted in an invalid object state.
Stubble makes things super easy by automatically stubbing out the key Active Record class and instance methods. This means less code in your tests.
Here’s an example that mixes Stubble and Shoulda:
Notice I did not need to set any attributes as part of the post. Again, Stubble automatically stubs the most common AR methods so the attributes would be ignored in the first place. Functionally, all I care about is what happens when a post results in a valid or invalid condition. Either I’ll be redirected (to the photos page) or back to the form itself (the :new action). I’ve completely decoupled the implementation details of my model from my controller test. So when my model changes in the near future, I most likely won’t have to update my functional tests.
Check out the Stubble GitHub project page for more examples.
After installing the Stubble gem, you’ll need to update test_helper.rb to leverage it:
About this entry
Posted: Wednesday, October 14th, 2009 at 10:58 pm
- Author:
- Phil Misiowiec
- Category:
- Solutions
- Tags:
- ruby on rails, shoulda, stubbing, testing
- License:
- Creative Commons

1 Comment
Jump to comment form | comments rss | trackback uri