Rspec Cucumber 中的模拟继续执行原始方法
Rspec Mocks in Cucumber keep executing original methods
我得到一个黄瓜步骤定义如下:
When(/^I click on the button to create a new target$/) do
RSpec::Mocks.with_temporary_scope do
dummy_connection = double('Dummy connection')
allow(dummy_connection).to receive(:add_target)
.and_return({ target_id: "ABCD" }.to_json)
allow(MyConnection).to receive(:retrieve_connection).and_return dummy_connection
click_button "Create"
end
end
在我的控制器中,我有一个小的 class 代理原始库 class:
class MyConnection
def self.retrieve_connection
Vws::Api.new(KEY, SECRET)
end
end
在执行测试时,"MyConnection.retrieve_connection" 尝试连接到 Web 服务,即使它已被删除。但是如果在测试中我写
MyConnection.retrieve_connection.inspect => #<Double "Dummy connection">
所以MyConnection.retrieve_connection
returns 虚拟连接,这是正确的。它只是在控制器中不起作用。
我没有想法,它似乎根本行不通。有什么提示吗?
发现我必须在 Cucumber Before
块中应用模拟才能使其工作。
但是,由于 MyConnection
class 是在第一次加载控制器后才定义的,所以我不得不直接模拟库函数:
Before do
dummy_connection = double("Dummy connection")
allow(dummy_connection).to receive(:add_target).and_return({ target_id: SecureRandom.hex(4) }.to_json)
allow(Vws::Api).to receive(:new).and_return(dummy_connection)
end
在黄瓜挂钩文件中 features/env/hooks.rb
。
这种方式似乎每次都有效。
我得到一个黄瓜步骤定义如下:
When(/^I click on the button to create a new target$/) do
RSpec::Mocks.with_temporary_scope do
dummy_connection = double('Dummy connection')
allow(dummy_connection).to receive(:add_target)
.and_return({ target_id: "ABCD" }.to_json)
allow(MyConnection).to receive(:retrieve_connection).and_return dummy_connection
click_button "Create"
end
end
在我的控制器中,我有一个小的 class 代理原始库 class:
class MyConnection
def self.retrieve_connection
Vws::Api.new(KEY, SECRET)
end
end
在执行测试时,"MyConnection.retrieve_connection" 尝试连接到 Web 服务,即使它已被删除。但是如果在测试中我写
MyConnection.retrieve_connection.inspect => #<Double "Dummy connection">
所以MyConnection.retrieve_connection
returns 虚拟连接,这是正确的。它只是在控制器中不起作用。
我没有想法,它似乎根本行不通。有什么提示吗?
发现我必须在 Cucumber Before
块中应用模拟才能使其工作。
但是,由于 MyConnection
class 是在第一次加载控制器后才定义的,所以我不得不直接模拟库函数:
Before do
dummy_connection = double("Dummy connection")
allow(dummy_connection).to receive(:add_target).and_return({ target_id: SecureRandom.hex(4) }.to_json)
allow(Vws::Api).to receive(:new).and_return(dummy_connection)
end
在黄瓜挂钩文件中 features/env/hooks.rb
。
这种方式似乎每次都有效。