Topic: Testing a find through association

Guys,

I've got a controller action that does a find for all for all of the solutions owned by a user in the following way, which I have tested with RSpec.

def index
      @solutions = Solution.find(:all, :conditions => {:user_id => @user.id})
  end

with the corresponding RSpec test:

      it "should find all of the solutions owned by a user" do
        Solution.should_receive(:find).with(:all, :conditions => {:user_id => @user.id}).and_return(@solutions)
        get :index, :user_id => @user.id
      end

However, I'd really like to use a find through association in my index action like this:

def index
      @solutions = @user.solutions.find(:all)
 end

so that its easier to read and more elegant, except I can't for the life of me figure out how I can write a spec that will test that correctly.

Can anybody point me in the right direction?

Joe

Joseph DelCioppio
Synantus Designs

Re: Testing a find through association

I thought I'd update this since I found the solution and maybe this will help someone else down the road.

The answer is an RSpec method called stub_chain.  This allows you to stub a chained method and specify what it should return. 

So if I wanted to stub the scoped solutions I can do something like this:

@user.stub_chain(:solutions, :find).with(:all).and_return(@solutions)

which would correctly stub

@solutions = @user.solutions.find(:all)

Hope this can help someone else in the near future.

Joe

Joseph DelCioppio
Synantus Designs