Reputation: 155
I'm looking to stub requests made with JavaScript in testing an external webpage. Puffing-billy looks to be the way to go - here's the code:
describe 'Covetable click behavior' do
let(:user) { create(:user) }
describe 'clicking button', :type => :feature, js: true do
it 'makes a request to our api' do
visit 'http://externaldomain.com'
allow_any_instance_of(Analytics::EventsController).to receive(:create)
sleep(7) # may be race conditions at work; helps following test pass
expect execute_script(typeof eventAnalytics == 'function').to eq true
# testing that the javascript making the request is loaded
proxy.stub('https://ourdomain/analytics/event').and_return(redirect_to: 'http://localhost:3000/analytics/event?name=$likeButtonClicked')
click_button 'Like'
expect_any_instance_of(Analytics::EventsController).to receive(:create)
end
end
end
Capybara.javascript_driver = :selenium_billy
config.around(:each, type: :feature) do |example|
WebMock.allow_net_connect!
VCR.turned_off { example.run }
end
Appreciate any suggestions for moving forward stubbing the requests!
Edit: updated the code, and added more in-depth logging.
The proxy stub doesn't raise an error directly, but does not intercept & redirect the http request being made. The test.log file either skips the request entirely or allows it: puffing-billy: PROXY GET succeeded for 'https://ourdomain.com:443/analytics/event...'
Failure/Error: Unable to find matching line from backtrace
Exactly one instance should have received the following message(s) but didn't: create`
I've also tried stubbing ourdomain.com:443, but it didn't seem to make a difference.
Upvotes: 1
Views: 835
Reputation: 49890
Capybara controls a browser and then the browser makes the requests, runs the javascript, etc. Because of that you can't stub the responses in the tests with stub_request because the browser doesn't know anything about that, it's just making requests to the server app. You can use puffing billy to redirect the requests from the browser, you will however need to make sure the proxy is getting correctly set in the driver. You can either do that manually when registering your own driver instance, or use one of the puffing billy provided driver setups (see the puffing billy readme for :selenium_billy, etc)
Upvotes: 1