I'm testing a Rails application using RSpec/Capybara and Webmock. I'm setting js:true
for a particular suite of tests, whilst stubbing out a web request using Webmock in a before block.
One of the tests fails intermittently - the error returned is that I haven't stubbed the web request (but I have!).
<WebMock::NetConnectNotAllowedError: Real HTTP connections are disabled... >
My tests are set up as follows:
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
If I change my main before block so that it signs in the user before setting the stub, the test passes, i.e this works:
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
I assume this is because the javascript server only starts running when start 'using it' i.e. when I sign the user in. So if I set my stubs before that point, they don't exist?
Anyway, I feel there must be a nicer way to fix this - a way I can still define my stubs before running some test code in a javascript test?
Any ideas would be appreciated!