我想从我的控制器测试模型方法。我正在尝试以下(简化代码):
model.rb
class Model < ActiveRecord::Base
def configure(threshold)
self.some_private_method(threshold) ## threshold is an int
end
end
models_controller.rb
def edit
case params.require(:threshold_string)
when 'low'
model.configure(1)
end
end
model_controller_spec.rb
RSpec.describe ModelsController, type: :controller do
describe 'PUT configure' do
let(model) {create :model}
let(:subject) { put :configure, threshold_string: 'low' }
it 'should receive a 1' do
model = spy('model')
subject
expect(model).to have_received(:configure)
end
end
end
运行测试时的错误消息
Failure/Error: expect(model).to have_received(:configure)
(#<Model:0x000000065ac0c0>).configure(*(any args))
expected: 1 time with any arguments
received: 0 times with any arguments
关于为什么间谍不起作用的任何想法?我也试过调用allow(model).to receive(:configure)
然后调用主题(并颠倒顺序)。任何帮助将非常感激。谢谢!
答案 0 :(得分:0)
在您的控制器中,您似乎希望将threshold_string
参数列入白名单。您可以使用params.permit(:threshold_string)
执行此操作。但是,这会返回{"threshold_string"=>"low"}
之类的哈希值,但与case
语句中的任何情况都不匹配。所以有两件事:
case params[:threshold_string]
put :configure, threshold_string: 'low'