首页 > 解决方案 > 如何更改 RSpec 的存根

问题描述

我有一个为此测试返回 422 的存根。这是为了生成一个询问用户是否确定要继续的模式。当他们单击“是,继续”时,我希望存根返回 200 并让测试将用户带回主页。我怎么能那样做?当我尝试放入我想要的存根时,似乎最后写入的存根是被使用的存根。好像我不能两者都做。似乎当单击保存退款确认按钮时,会再次调用 422 存根。我希望使用 200 存根。

scenario 'successfully saves refund when user clicks yes continue on similar refund', js: true do
      save_payer_refund_success_request = stub_request(:post, /remittances/).to_return(status: 200)
      save_payer_refund_fail_request = stub_request(:post, /remittances/).to_return(status:422, body: {error: "SIMILAR_REMITTANCE"}.to_json)
      visit record_refund_check_by_payer_remittances_path

      #Test fils out the form here

      page.find_by_id('refund_record').click
      wait_for_ajax
      expect(save_payer_refund_fail_request).to have_been_made # <--- This works
      expect(page).to have_content 'A refund from this payer with this number with the amount of $' + @refundTotalAmount + ' and date of ' + @EFTCheckDate + ' already exists in Value-Based Reimbursement. Are you sure you want to record this refund?'
      page.find_by_id('save-refund-confirmation-button').click
      wait_for_ajax
      expect(save_payer_refund_success_request).to have_been_made # <--- Fails here
      expect(page).to have_content 'Refund check ' + @checkNumber + ' to payer has been saved.'

标签: ruby-on-railstestingruby-on-rails-5capybararspec-rails

解决方案


如果您想stub_request为对同一匹配端点的连续调用返回不同的响应,那么您需要在一次stub_request调用中指定所有这些响应 - https://github.com/bblimke/webmock#multiple-responses-for-repeated-requests

my_request = stub_request(:post, /remittances/).
  to_return(status: 200).then.
  to_return(status:422, body: {error: "SIMILAR_REMITTANCE"}.to_json)
...
expect(my_request).to have_been_requested.times(2)

注意:这只是你的应用程序/测试发出的存根请求(所以我假设你的应用程序内部回调到它自己的 API)——这实际上并不是你在 Capybara 上使用的任何浏览器发出的存根请求


推荐阅读