[rspec-users] collection-based finder methods

David Chelimsky dchelimsky at gmail.com
Wed Jul 22 09:13:59 EDT 2009

On Tue, Jul 21, 2009 at 11:21 PM, amkirwan<amkirwan at gmail.com> wrote:
> How do I spec this following example from the Agile Rails Book listed
> below. I am doing a similar thing in my controller and when I
> attempted to change it to the collection way of doing the find I am
> unable to get my spec to pass though I know it is working fine as my
> cucumber features are passing
> old rails way:
> def show
> @order = Order.find(params[:id])
> end
> new rails way collection-based:
> def show
> id = params[:id]
> @order = @user.orders.find(id)

This code is inherently untestable in an isolated/granular way. Your
options are:

* write higher level specs that use real data
  * pros: simplicity and clarity in both code and specs
  * cons: brittle due to runtime dependency on correct models, runs slow

* write a very invasive spec with complex setup and instance_eval to
set up the @user
  * pros: runs fast, no runtime dependency on correct models
  * cons: brittle due to dependency on internals, complex

* refactor the code to make it easier to spec
  * pros: more highly decoupled code, simpler specs, fast
  * cons: more work up front, may disregard some of what Rails has to offer

Note that the first two options are both brittle, but for different
reasons. The first is brittle due to a runtime dependency. That means
that when you run the spec the model has to be working correctly for
the spec to pass, and a failure could be due to a problem in the model
or in the controller.

The second is due to a code dependency. That means that when you want
to change this code, the spec will have to change as well. This is
true of any case in which you use mocks or stubs to varying degrees,
and that comes with its own tradeoffs. In this case, the necessary
stubbing would be complex and invasive enough that it would be a
concern to me.

Getting to your original question - what does your spec look like now,
and what failure message are you getting?


> rescue
> redirect_to :action => "index"
> end
> _______________________________________________
> rspec-users mailing list
> rspec-users at rubyforge.org
> http://rubyforge.org/mailman/listinfo/rspec-users

More information about the rspec-users mailing list