如何允许模拟控制器中的本地范围变量来接收消息?
所以,我只用了几天的 Ruby。任何提示将不胜感激。
变量rb
class Variable < ApplicationRecord
def some_attribute=(value)
#do something with the vlue
end
end
X_Controller.rb
class XController < ApplicationController
def do_something
variable = Variable.instance_with_id(params[:id])
variable.some_attribute = some_new_value
redirect_to(some_url)
end
end
x_controller_spec.rb
describe '#do_something' do
before do
allow(Variable).to receive(:instance_with_id) # Works fine
allow_any_instance_of(Variable).to receive(:some_attribute)
post :do_something, :params => { id: 'uuid' }, :format => :json
end
it {
expect(variable).to have_received(:some_attribute)
}
end
回答
你可能想要这个:
let(:variable) { instance_double("Variable") }
before do
allow(Variable).to receive(:instance_with_id).and_return(variable)
allow(variable).to receive(:some_attribute=)
# ...
end
因为instance_with_id应该返回一些东西。然后您希望允许在该实例上调用some_attribute=(注意=)。