如何允许在控制器中模拟局部范围的变量来接收消息?
How do I allow mock a locally scoped variable in a controller to receive a message?
所以,我只做了 Ruby 几天。任何提示将不胜感激。
variable.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
应该 return 一些东西。然后你想允许在那个实例上调用 some_attribute=
(注意 =
)。
所以,我只做了 Ruby 几天。任何提示将不胜感激。
variable.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
应该 return 一些东西。然后你想允许在那个实例上调用 some_attribute=
(注意 =
)。