【问题标题】:how to access request's headers using minitest with Rails?如何使用带有 Rails 的 minitest 访问请求的标头?
【发布时间】:2021-08-17 12:06:39
【问题描述】:

我有如下测试环境配置

ENV['RAILS_ENV'] ||= 'test'
require_relative '../config/environment'
require 'rails/test_help'
require 'minitest/rails'

# Consider setting MT_NO_EXPECTATIONS to not add expectations to Object.
# ENV["MT_NO_EXPECTATIONS"] = true

Dir[Rails.root.join('test/support/**/*.rb')].each { |f| require f }

class ActiveSupport::TestCase
  # Run tests in parallel with specified workers
  # parallelize(workers: :number_of_processors)

  # Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order.
  fixtures :all

  # Add more helper methods to be used by all tests here...
end

以及下面的测试

describe Abi::OrganizationsController do
  before do
    @request.headers['x-abi-token'] = 'test'
  end

  describe '#create' do
    let(:credit_rating) { 'A' }
    let(:organization_data) do
      {
        organization: {
          name: 'Test Organization',
          ....
    end

    it 'should return an organization id' do
      post(abi_organizations_path, params: organization_data)
    end
  end
end

在需要发送新标头之前,测试工作正常。

我尝试使用 @request.headers,但此时,@requestnil,我尝试过的没有任何实际帮助。

当我将课程更新为此时,我设法获得了 @request

class Abi::OrganizationsControllerTest < ActionController::TestCase

但是,我不得不把话题改成这样:

post :create, params: organization_data # <-- new subject
# post(abi_organizations_path, params: organization_data)

这是我不想做的事情,然后我开始看到这个错误

RuntimeError Exception: @controller is nil: make sure you set it in your test's setup method.

我有点迷路了,我在互联网上没有找到任何有用的东西,我觉得我是唯一一个遇到这个没有任何意义的问题的人。

以前有人试过吗?

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-6 minitest


    【解决方案1】:

    这是来自 Rails 中的这种健全性检查。

    https://github.com/rails/rails/blob/18707ab17fa492eb25ad2e8f9818a320dc20b823/actionpack/lib/action_controller/test_case.rb#L629-L637

    我最好的选择是您的测试类名称与任何控制器名称都不匹配。您的测试类称为Abi::OrganizationsControllerTest,因此Rails 将假定一个控制器类,如Abi::OrganizationsController

    https://github.com/rails/rails/blob/18707ab17fa492eb25ad2e8f9818a320dc20b823/activesupport/lib/active_support/testing/constant_lookup.rb#L36

    【讨论】:

    • 我三重检查并且类名匹配。这就是为什么我会为此烦恼
    • 在rails代码中添加一些puts,例如bundle open active_support
    • 我得到了错误:根据文档,@request 仅在发出请求后可用。在这里做我想做的事是不可能的。无论如何我都会接受答案,因为我今天学到了一些新东西。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2016-08-08
    • 2019-06-04
    • 2016-10-25
    • 2014-02-15
    • 2022-11-10
    • 1970-01-01
    • 2018-11-13
    相关资源
    最近更新 更多