使用js时,Rspec模拟在before块中被忽略:是吗?

时间:2019-01-07 10:52:58

标签: rspec capybara rspec-rails webmock

我正在使用RSpec / Capybara和Webmock测试Rails应用程序。我正在为一组特定的测试设置js:true,同时在before块中使用Webmock发出Web请求。

其中一项测试间歇性失败-返回的错误是我没有对Web请求进行存根(但是我有!)。

<WebMock::NetConnectNotAllowedError: Real HTTP connections are disabled... >

我的测试设置如下:

RSpec.feature 'Viewing something', type: :feature, js: true do
  before do
    body = { 'report': [{ 'data': [1,2,3] }] }.to_json
    stub_request(:post, 'https://www.some-url.com').to_return(status: 200, body: body, headers: {'Content-Type' => 'aplication/json'})
    sign_in_user
  end
  # Failing test:
  it 'does something' do
    expect(page).to have_text 'Something'
  end
  # Passing test:
  context 'With a different stubbed result' do
    before do
      body = {'report': []}.to_json
      stub_request(:post, 'https://www.some-url.com').to_return(status: 200, body: body, headers: {'Content-Type' => 'aplication/json'})
    end
    it 'shows something else do
      expect(page).to have_text 'Something else'
    end
  end
end

如果我更改main之前的代码块,以便它在设置存根之前登录用户,则测试会通过,即可以:

before do
    sign_in_user
    body = { 'report': [{ 'data': [1,2,3] }] }.to_json
    stub_request(:post, 'https://www.some-url.com').to_return(status: 200, body: body, headers: {'Content-Type' => 'aplication/json'})
end

我认为这是因为javascript服务器仅在开始“使用它”时(即当我登录用户时)才开始运行。因此,如果我在那之前设置了存根,它们不存在吗?

无论如何,我觉得必须有一种更好的方法来解决此问题-在javascript测试中运行一些测试代码之前,我仍然可以定义存根?

任何想法将不胜感激!

0 个答案:

没有答案