[rspec-users] Drawing the line between controller and integration tests

Cynthia Kiser cnk at ugcs.caltech.edu
Tue Sep 11 20:25:15 UTC 2012


Quoting Fearless Fool <lists at ruby-forum.com>:
> I'm trying to understand what belongs -- and what doesn't belong -- in
> controller tests and in integration tests.
> 
> As a common example, assume I have a list of named widgets.  Somewhere
> in my code, I want to verify that
> 
>     widget = FactoryGirl.create(:widget)
>     get :index
> 
> generates a page that has the string #{widget.name} somewhere therein.
> But is that a controller test or an integration test?

First, one of the other responses in this thread split the world into
unit tests vs integration tests. For the most part, the tests
generated by the Rails framework are all set up to be unit tests
(provided you use mocks and stubs instead of the supporting objects
that you are not directly testing in a particular file). 

In your example above, since you created the object instead of using a
stub or mock, this is an integration test, not a straight unit test
for the controller. This test could fail for reasons having nothing to
do with the controller (e.g. you added a required field ot the widget
model and forgot to update your factory) - that makes it an
integration test. To make that into a controller unit test, you need
to mock the widget and just test that the controller makes available
an instance variable containing 'widget'. Then you need a view spec
that provides a mock for the @widget variable and then makes sure that
the view displays the widget name.

Or, as one of the other people pointed out, make an integration test
that does all of what you outlined above. 

> As another example, assume a user must be logged on in order to access
> the widgets.  I can test authentication and authorization separately,
> but is it considered necessary to write an integration test for this?
> Or is this something you'd verify at the controller level?

I usually take the road mentioned by one of the other respondents and
create a separate file containing my authorization tests. Because in
that file I am only focusing on the return status from the request, I
am more or less making unit tests for my authorization configuration.

> One addendum: One thing I'd specifically like to know is where/how
> do you test the *contents* of generated responses?  That seems
> beyond the purview of a controller test, but it doesn't require
> multiple transactions or cross-controller interactions that would
> require an integration test.

In a Rails context, you test the contents of the generated responses
in view tests.  

-- 
Cynthia N. Kiser
cnk at ugcs.caltech.edu


More information about the rspec-users mailing list