在RSpec中关闭“期望接收”

时间:2019-02-21 23:20:39

标签: rspec stubbing

我对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

如何删除,替换或禁用对新规范的期望?

1 个答案:

答案 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