Ruby-on-rails – RSpec any_instance deprecation: how to fix it

rspecrubyruby-on-railstesting

In my Rails project I'm using rspec-mocks using any_instance but I want to avoid this deprecation message:

Using any_instance from rspec-mocks' old :should syntax without explicitly enabling the syntax is deprecated. Use the new :expect syntax or explicitly enable :should instead.

Here is my specs:

describe (".create") do
  it 'should return error when...' do
    User.any_instance.stub(:save).and_return(false)
    post :create, user: {name: "foo", surname: "bar"}, format: :json
    expect(response.status).to eq(422)
  end
end

Here is my controller:

def create
    @user = User.create(user_params)
    if @user.save
      render json: @user, status: :created, location: @user
    else
      render json: @user.errors, status: :unprocessable_entity
    end
end

I'd like to use the new :expect syntax but I can't find how to use it properly.

I'm using RSpec 3.0.2.

Best Answer

Use allow_any_instance_of:

describe (".create") do
  it 'returns error when...' do
    allow_any_instance_of(User).to receive(:save).and_return(false)
    post :create, user: {name: "foo", surname: "bar"}, format: :json
    expect(response.status).to eq(422)
  end
end