Nested Resource testing RSpec

Posted by Joseph DelCioppio on Stack Overflow See other posts from Stack Overflow or by Joseph DelCioppio
Published on 2010-03-28T17:14:14Z Indexed on 2010/03/28 17:23 UTC
Read the original article Hit count: 244

I have two models:

class Solution < ActiveRecord::Base
  belongs_to :owner, :class_name => "User", :foreign_key => :user_id
end                  

class User < ActiveRecord::Base
  has_many :solutions
end

with the following routing:

map.resources :users, :has_many => :solutions

and here is the SolutionsController:

class SolutionsController < ApplicationController
  before_filter :load_user

  def index
    @solutions = @user.solutions
  end

  private
    def load_user
      @user = User.find(params[:user_id]) unless params[:user_id].nil?
    end
end

Can anybody help me with writing a test for the index action? So far I have tried the following but it doesn't work:

describe SolutionsController do
  before(:each) do
    @user = Factory.create(:user)
    @solutions = 7.times{Factory.build(:solution, :owner => @user)}
    @user.stub!(:solutions).and_return(@solutions)
  end

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

And I get the following error:

Spec::Mocks::MockExpectationError in 'SolutionsController GET index, when the user owns the software he is viewing should find all of the solutions owned by a user'
#<User:0x000000041c53e0> expected :solutions with (any args) once, but received it 0 times

Thanks in advance for all the help.

Joe

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about rspec