[rspec-users] (rspec2/rails3) spec'ing the details of a controller that is not purely *skinny* by design.

Wincent Colaiuta win at wincent.com
Thu Jul 8 12:43:30 EDT 2010

El 08/07/2010, a las 18:17, Frank J. Mattia escribió:

> My controller does something like this for create
> @object = Object.new(params[:object])
> @object.created_by = current_user
> if @object.save... yadda yadda yadda...
> I have my model spec testing for the presence of created_by but I feel
> compelled to test that my controller is correctly setting current_user
> on its appropriate actions. Does this seem reasonable? If so, what's
> the proper way to test it?

Seems reasonable to me. You could test with either an interaction based approach (use mocks and stubs to confirm that @object receives the "created_by" message with the expected param) or a state based approach (hit the controller action and then inspect the system state afterwards to confirm that it is in the expected state).

Interaction based approach:

- may seem like more work due to the set-up of the mocks and stubs

- runs faster because you can make it so that your controller test doesn't even hit the database

- may cause you to replicate internal implementation details in your tests

- may shield you from finding out about actual breakage in your system because it insulates your controller from the actual API on the real mocked/stubbed class

State based approach:

- may seem like less work due to easier set-up

- may run slower, which can be important if you have an enormous spec suite

- helps focus your specs on externally observable behavior rather than internal implementation details

- couples your controller tests to your actual model instances, so breakage in your models will cause more than just model specs to fail

Personally I prefer a state based approach in general, but I look at things on a case-by-case basis. Generally if I pick the wrong one I soon find out about it because the specs I end up writing are stomach-churning.

And there is a feedback loop here too: if _both_ of these approaches seem difficult, then it is a sign that the code you're testing could probably be rethought to make it more easily testable.


More information about the rspec-users mailing list