Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rspec: How to stub private method?

Here is the error:

private method `desc' called for #<Array:0x0000010532e280>

the spec:

describe SubjectsController do  
  before(:each) do
    @subject = mock_model(Subject)
  end

    describe "#0002 - GET #index" do
    before(:each) do        
      subjects = [@subject, mock_model(Subject), mock_model(Subject)]
      Subject.stub!(:all).and_return(subjects)
      Subject.all.stub!(:desc).and_return(subjects)
      get :index
    end

    it { response.should be_success }
    it { response.should render_template("index") }
  end
end

and the controller:

def index
  @subjects = Subject.all(conditions: {company_id: current_user.company.id}).desc(:created_at)
end

I don't know how to solve this issue, can some one give me a hand ? Could you also give me advise on how you would test this method ? Thx.

like image 310
Pierre-Louis Gottfrois Avatar asked Jun 15 '11 14:06

Pierre-Louis Gottfrois


2 Answers

It's a little more mocking & chaining than I prefer but, you can do this:

subjects = [...]
desc_mock = double("desc order mock")
desc_mock.should_receive(:desc).with(:created_at).and_return(subjects)

conditions = {...}
Subject.should_receive(:all).with(conditions).and_return(desc_mock)

You could also simplify this a lot by moving your query into a named scope that takes some parameters. Then your test could verify that Subject received your scope with the correct parameters like:

Subject.should_receive(:user_company).with(current_user.id).and_return(subjects)
like image 86
jdeseno Avatar answered Oct 13 '22 21:10

jdeseno


stub_chain should work here:

  Subject.stub_chain(:all,:desc) { [mock_model(Subject)]*2 }
like image 20
zetetic Avatar answered Oct 13 '22 20:10

zetetic