RSpec/rails 未设置请求 headers

RSpec/rails not setting request headers

问题

我正在设置测试,使用 RSpec,用于 api,使用 rails。在其中一项测试中,我试图添加一些身份验证 headers,但 headers 似乎无法满足我的请求。我怎样才能正确传递那些 headers?

我需要传3 headers (client, access-token and uid ) 因此系统将用户识别为已登录。如果我没有通过,我会得到系统未登录 error message

如果我在 postman 上手动尝试访问相同的端点,即我正在测试的端点,并简单地传递 headers、it works

代码

RSpec.describe Api::V1::Profiles::CreditCardsController, type: :api do
  describe 'POST /api/v1/profiles/credit_cards' do
    let!(:profiles) {FactoryGirl.create_list(:profile, 1)}
    it 'Usuário cadastrando cartão no sistema' do
      number = Faker::Stripe.valid_card
      params = {
          :number => number,
          :expiration_date => Faker::Stripe.year + '/' + Faker::Stripe.month,
          :brand => 'Visa',
          :proper_name => Faker::Name.name,
          :cvv => Faker::Stripe.ccv,
      }
      headers = auth_headers(profiles[0])
      requisicao = post '/api/v1/profiles/credit_cards', params, headers  
      # byebug
      expect(last_response.status).to eq(200)
    end
  end

结果

在我的 byebug 期间,如果我访问我的变量 headers,这是我要添加的变量,我设置了正确的东西:

{"access-token"=>"eQV4yjzKU7cfCgD2kLcMPQ", "client"=>"FWJQNb-aRFD6lmYW1MU8Sw", "uid"=>"ericrice@feeney.com"}

注:以上数值并非真实数值,由factory girl library

生成

但是,当我访问我的 请求时 headers 它们没有出现:

{"X-Frame-Options"=>"SAMEORIGIN", "X-XSS-Protection"=>"1; mode=block", "X-Content-Type-Options"=>"nosniff", "Content-Type"=>"application/json; charset=utf-8", "Cache-Control"=>"no-cache", "X-Request-Id"=>"0ed4657c-507d-4033-bc20-81d452de0d1b", "X-Runtime"=>"0.004898", "Date"=>"Wed, 16 Jan 2019 16:43:03 GMT", "X-Rack-Cache"=>"pass", "Vary"=>"Origin", "Content-Length"=>"59"}

更新

第一次更新

我尝试从 type :api 切换到 type :requesttype :api 包括 Rack::Test::Methods,这弄乱了我的响应变量,正如@所指出的januszm 在评论 here 中。但是,起初这似乎对我的情况没有任何影响。但我坚持测试并发现确实解决了我的问题。

从类型 :api 切换到类型 :request 让我可以访问 requestresponse 变量,之前,我必须自己创建变量才能尝试访问它们。

当使用 type :api 时,我可以访问 last_response 而不是 response,因为我的 type :api 包括 Rack::Test::Methods,这很乱根据 this post.

增加这些变量(响应和请求)

当我切换到 type :request 并且不再导入 Rack::Test::Methods 时,我能够访问 request 变量并看到所需的 headers 已正确添加。