BDD and Setting Up Controllers
I started using Rick Olson’s simply_bdd plugin about a month ago. Soon after, I added a method to it and emailed Rick the suggested update. He responded by pointing me to the really sweet test/spec lib and said he may begin using that instead. I gave it a try and fell in love. I like rSpec but I’m not quite ready to jump on the band wagon. test/spec gives me bdd style contexts and specifications while still allowing me to use the assertions from test/unit.
The first thing I noticed as I switched mindsets from tests to specs is that I end up with several smaller contexts as opposed to one massive test case. For unit tests, this doesn’t really change much but with functional tests it does as there is typically more setup. I’m still trying to figure out my “default” contexts for controllers but whatever the case, I always have at least 4 or 5 contexts per controller. Each of these contexts has to setup the controller like so:
context "Some Context" do setup do @controller = SomeController.new @request = ActionController::TestRequest.new @response = ActionController::TestResponse.new # get, post, put or delete some action or whatever else i need for the context ... end end
I know there are arguments for and against repeating yourself in your tests. Some people think it’s horrible, others don’t care. Personally, I just hate typing (and even copying) large amounts of text. Now, I always add the following method to my test_helper.rb file:
def setup_controller(controller) @controller = controller.new @request = ActionController::TestRequest.new @response = ActionController::TestResponse.new end
Now my setup method looks like this:
context "Some Context" do setup do setup_controller(SomeController) # get, post, put or delete some action or whatever else i need for the context ... end end
One line replaces three. This may not seem like a big deal but when you hate typing as much as me, it comes in pretty handy. I have a plugin I always install which has all my typical test helpers (including this one) and you can grab it from svn.
Update: The test_spec_on_rails plugin has a use_controller method that pretty much negates this post.