【问题标题】:Why is Rails.logger nil in test environment?为什么 Rails.logger 在测试环境中为零?
【发布时间】:2016-05-17 13:02:00
【问题描述】:

更新:以下似乎是rake test 运行我的单元测试时未加载 Rails 环境的结果(当前只有一个位于 /lib 中的模块)。是否可以从命令行包含环境,而不是更改 rake 任务本身?有没有更好的方法来解决这个问题(不使用依赖注入来引入 Rails.logger,我可能最终会这样做)?

由于以下对Rails.logger.error 的调用,我在测试环境中看到NoMethodError

# /lib/square.rb

module Square

  def self.get_total_sales_for_location(location_id, timeout: 5)
    begin
      url = "https://connect.squareup.com/v2/locations/#{location_id}/transactions"
      headers = {Authorization: "Bearer #{ENV['SQUARE_PERSONAL_ACCESS_TOKEN']}"}
      response = RestClient::Request.execute  headers: headers,
                                              method: :get,
                                              timeout: timeout,
                                              url: url

      if response.code == 200
        JSON.parse response.body
      else
        fail
      end
    rescue => error
      Rails.logger.error "Square::get_total_sales_for_location - #{error.message}"
      raise
    end
  end
end

这一切都可以从控制台正常运行,但是运行我的测试会导致:NoMethodError: undefined method 'error' for nil:NilClass

我的 临时 解决方法是使用 :try 来防止异常,但这非常笨拙。

【问题讨论】:

  • 在您的代码示例中,您使用的 Rails.logger.log 不起作用
  • 使用 Rails.logger.info 或 Rails.logger.debug
  • 感谢您指出这一点。我的代码实际上使用了“错误”,但在翻译中丢失了。
  • 你真的在这个测试的上下文中加载 Rails 吗?因为该文件存储在 lib 文件夹中,所以我希望它不依赖于 Rails,并且在测试时不会加载 Rails...
  • 这很好。我假设提供的“rake test”任务会。我会尝试在 Rails 源代码中挖掘它。

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


【解决方案1】:

你可以rake environment test。但我猜如果使用task test: :environment do 使测试任务依赖于环境会更好

【讨论】:

    猜你喜欢
    • 2012-02-17
    • 1970-01-01
    • 1970-01-01
    • 2017-12-02
    • 2022-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多