【问题标题】:RSpec/rails not setting request headersRSpec/rails 未设置请求标头
【发布时间】:2019-01-16 17:04:15
【问题描述】:

问题

我正在使用 RSpec 为使用 rails 制作的 api 设置测试。在其中一项测试中,我正在尝试添加一些身份验证标头,但是这些标头似乎无法满足我的请求。如何正确传递这些标头?

我需要传递 3 个标头(clientaccess-tokenuid),以便系统将用户识别为已登录。如果我不通过,我会得到系统未登录error message

如果我在 postman 上手动尝试访问相同的端点,即我正在测试的端点,并简单地传递标头 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库生成的

但是,当我访问我的 请求标头时,它们并没有显示出来:

{"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 中所指出的那样,这弄乱了我的响应变量。但是,起初这似乎对我的情况没有任何影响。但我坚持测试并意识到这确实解决了我的问题。

【问题讨论】:

    标签: ruby-on-rails rspec rspec-rails


    【解决方案1】:

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

    当使用 type :api 时,我可以访问 last_response 而不是 response,因为我的 type :api 包括 Rack::Test::Methods,根据this post,这会弄乱这些变量(响应和请求)。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-28
      • 2011-06-24
      • 1970-01-01
      • 2020-07-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多