Matt Gibson
Matt Gibson

Reputation: 14949

Correct way to stub a class method with a mock object that has a expectation set on it in Rspec 3

Here's a working test, which Rspec tells me is now wrong because stub! is deprecated:

it 'paginates the right number of times' do
  mock_thing = mock_model(User)
  User.stub!(:page).and_return(mock_thing)
  mock_thing.should_receive(:per).with(50)
  get :index
end

What's the right way to do this? I tried the code below, but it fails:

it 'paginates the right number of times' do
  mock_thing = mock_model(User)
  mock_thing.should_receive(:per).with(50)
  User.stub(:page, mock_thing) do
    get :index
  end
end

# Error:
# RSpec::Mocks::MockExpectationError: Double "User_1001" received unexpected 
# message :[]= with (:expected_from, ...Stacktrace removed

Upvotes: 0

Views: 1506

Answers (1)

Peter Alfvin
Peter Alfvin

Reputation: 29419

The problem statement is:

User.stub!(:page).and_return(mock_thing)

which requires the monkey patching of Object to support the stub method.

You can explicitly enable the should syntax to get around the deprecation warning, but the way to express this with the new syntax is:

allow(User).to receive(:page).and_return(mock_thing)

I haven't reviewed the rest of your example for reasonableness.

Upvotes: 1

Related Questions