我对RSpec的期望是在before
块中设置的:
context 'my_context' do
before :each do
expect(Net::HTTP).to receive(:new).at_least(:once)
end
it_behaves_like MyClient
end
但是,我刚刚添加了一段代码,这意味着Net::HTTP
在特定情况下不会不接收此消息。 (注意:shared_examples
块已经存在。)
shared_examples MyClient do
it 'new code returns a 404 before creating a Net::HTTP' do
# I want to remove the expectation here
trigger_the_new_use_case
expect(response).to be_not_found
end
it 'does other stuff'
end
我尝试添加此行以覆盖期望值:
expect(Net::HTTP).not_to receive(:new)
...但是它只是增加了另一个期望;原始的仍然存在,并且仍然失败。
如果可能的话,我也不太清楚如何使用元数据来做到这一点。我试图拆分before
块:
before :each do
other_setup_stuff
end
before :each, wont_create_net_http: false do
# I had hoped that `false` would act as a default value - I can't specify it in
# hundreds of other tests - but it didn't. `nil` didn't either.
expect(Net::HTTP).to receive(:new).at_least(:once)
end
before :each, wont_create_net_http: true do
# This one worked OK
expect(Net::HTTP).not_to receive(:new)
end
it 'new spec', :wont_create_net_http do
run_the_spec
end
如何删除,替换或禁用对新规范的期望?
答案 0 :(得分:0)
此 可以通过使用元数据为此特定示例设置不同的期望来完成,但是您需要在around
块中访问元数据并将其保存以备后用:>
context 'my_context' do
# Extract metadata
around :each do |example|
@example_wont_create_net_http = example.metadata[:wont_create_net_http]
example.run
end
before :each do
other_setup_stuff
if @example_wont_create_net_http
expect(Net::HTTP).not_to receive(:new)
else
expect(Net::HTTP).to receive(:new).at_least(:once)
end
end
it_behaves_like MyClient
end
shared_examples MyClient do
it 'new code returns a 404 before creating a Net::HTTP', :wont_create_net_http do
trigger_the_new_use_case
expect(response).to be_not_found
end
# other examples don't change
end