2

我遇到了 webmocks 存根的问题。

这是一个使用 devise/cancan 进行身份验证和授权的 Rails 4 应用程序。我正在使用 RSpec 编写测试。

我有一个(为了这篇文章的原因而简化了!)我想运行的测试。

require 'rails_helper'

RSpec.describe ApiChecksController, type: :controller do

  include Devise::TestHelpers

  let(:user)          { FactoryGirl.create :user }
  let(:api_params) do
    {
      param_1: 'VALUE',
      param_2: '1980-01-01',
      param_3: 'AA123',
      param_4: "#{Date.today}"
    }
  end

  context 'logged in as standard user' do
  describe 'POST #lookup' do
      context 'displays error' do
        it 'when 500 returned' do
          WebMock.disable_net_connect!(allow: 'codeclimate.com')
          sign_in user
          stub_request(:post, "#{ENV['API_PROXY']}/api/checks").
            to_return(status: [500, "Internal Server Error"])
          post(:lookup, api_check: api_params)
          expect(response.status).to eq(500)
        end
      end
    end
  end
end

在完整的测试套件中,expect 语句之上的所有内容都是使用 let 或 set in before 块设置的。我试图将其提炼成最小的选项,但测试仍然失败。

问题

我期待

stub_request(:post, "#{ENV['API_PROXY']}/api/checks").
  to_return(status: [500, "Internal Server Error"])

始终返回 500 状态响应,但它返回 200。

我的预期正确吗?这是应该如何调用 webmocks 的吗?

4

1 回答 1

4

您需要将查询参数添加到stub_request方法中,您可以将其更改为这样

stub_request(:post, "#{ENV['API_PROXY']}/api/checks")
  .with(query: {api_check: api_params})
  .to_return(status: [500, "Internal Server Error"])
于 2015-04-09T10:44:15.170 回答