【问题标题】:Requests in external Capybara integration testing外部 Capybara 集成测试中的请求
【发布时间】:2015-09-17 20:24:17
【问题描述】:

我正在寻找在测试外部网页时使用 JavaScript 发出的存根请求。 Puffing-billy 看起来是要走的路 - 这是代码:

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

感谢任何有关推进存根请求的建议!

编辑:更新了代码,并添加了更深入的日志记录。

代理存根不会直接引发错误,但不会拦截和重定向正在发出的 http 请求。 test.log 文件要么完全跳过请求,要么允许它: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`

我也尝试过存根 ourdomain.com:443,但似乎没有什么不同。

【问题讨论】:

    标签: rspec capybara integration-testing


    【解决方案1】:

    Capybara 控制浏览器,然后浏览器发出请求、运行 javascript 等。因此,您不能使用 stub_request 对测试中的响应进行存根,因为浏览器对此一无所知,它只是在制作对服务器应用程序的请求。您可以使用 puffing billy 重定向来自浏览器的请求,但是您需要确保在驱动程序中正确设置了代理。您可以在注册自己的驱动程序实例时手动执行此操作,也可以使用 puffing billy 提供的驱动程序设置之一(请参阅 puffing billy 自述文件:selenium_billy 等)

    【讨论】:

    • 感谢您的指导 - 我一直在处理 puffing-billy 配置,但尚未让 puffing-billy 识别和重定向请求。我已经尝试将 :selenium_billy 和 :selenium_chrome_billy 作为水豚的驱动程序。
    • 你确定它没有重定向,还是你说你的期望没有成功?如果后者 - 是否会在 GET 上调用该 URL 的 create ? (重定向仅作为 GET 请求发送 - 而不是通常用于创建操作的 POST) - 如果它真的根本没有重定向 - 请将您问题中的代码更新为您现在正在使用的代码 - 包括你在哪里设置水豚驱动程序
    • 是的,get 请求被发送到 events#create。根据您的要求更新了代码。
    • Puffing-billy 如果传递了一个字符串,则在剥离查询参数(假设您没有更改 strip_query_params 的默认值)后对 url 进行精确的字符串匹配 - 所以它必须与之前的所有内容完全匹配?您也可以传递一个正则表达式,所以也许可以尝试 proxy.stub(/ourdomain\.com/).and_return(...) 以确保匹配正常
    • 还有。您正在重定向到端口 3000 - 这通常是人们的开发服务器端口,而不是水豚运行其应用程序副本的端口。如果您的设置中出现这种情况,则期望将不起作用,您需要将其重定向到应用程序实例 capybara 启动
    猜你喜欢
    • 2017-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-24
    • 2022-01-24
    • 2015-09-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多