I'm trying to stub a method that's called inside a controller, but it only gets stubbed within the test and not when it's called in the controller.
Target method:
class MyModel < ApplicationRecord
def self.fetch_boolean(arg)
MyModel.find_by({ name: arg })
MyModel.value
end
end
Target controller:
# controller
class OtherModelController < ApplicationController
# ...
if MyModel.fetch_boolean('123')
# do something
end
# ...
end
RSpec test:
describe 'test' do
before(:each) do
allow(MyModel).to receive(:fetch_boolean).with('123').and_return(true)
end
it 'should do something' do
get :show
expect(response).to eq('hello')
end
end
I called debugger within the RSpec test and called MyModel.fetch_boolean and got true. However, when I called it inside the controller, I got false (which is the stored value).
How do I make sure that the method inside the controller also gets stubbed?
RSpec version 3.7
Update:
Other stubbing syntaxes I've tried
allow(MyModel).to receive(:fetch_boolean).with('123') { true }
# same outcome
allow_any_instance_of(MyModel).to receive(:fetch_boolean).with('123') { true }
# error: MyModel does not implement #fetch_boolean
controller.stub(MyModel.fetch_boolean).with('123') { true }
# error: Wrong number of arguments. Expected 1, got 0
controller.stub(MyModel.fetch_boolean('123')) { true }
# error: true is not a symbol nor a string