Get a response of Webmock in capybara system test.

problem

This article will introduce how to get a response in a system test, which means I want to check out whether the chrome driver(I use this driver) automatically kick a correct request. In webmock docs, the explanation is like below.

stub_request(:get, 'www.example.com').
with(headers: {'Accept' => ['image/jpeg', 'image/png'] })

req = Net::HTTP::Get.new("/")
req['Accept'] = ['image/png']
req.add_field('Accept', 'image/jpeg')
Net::HTTP.start("www.example.com") {|http| http.request(req) } # ===> Success

However, this is not useful in a system test.(I might lack learning…) because the test above kick a request api in a test itself. I wrote the code that calls api in an application. I don’t want to call the request in a test.

# system testbefore do
stub_request(:post, "https://example.com").to_return(status: 200)
end
it 'calls api and return 200' do
# I don't want to use Net::HTTP::Get.new("https://example.com")
expect(res.status). to eq 200
end

solution

Actually, it is possible to get a response in a system test by writing code like below.

# system testbefore do
@res = stub_request(:post, "https://example.com").to_return(status: 200)
end
it 'calls api and return 200' do
expect(@res.response.status[0]).to eq 200
end

res became an instance variable and can be used in ‘it ~ end’. Moreover, status code can be gotten with the code. We can test the status.

My LinkedIn account is below! Please contact me!

https://www.linkedin.com/in/tomoharu-tsutsumi-56051a126/