【问题标题】:How can I test using rails params outside controller rails如何在控制器导轨外使用导轨参数进行测试
【发布时间】:2013-06-15 16:27:31
【问题描述】:

我在 /rails_root/lib/common/common_log.rb 中创建了一个模块 并将其包含在 ApplicationController 中, 从我的控制器调用它通常结束。 然后我做了rspec。但有一个错误。 我不明白如何在规范文件中编写参数。 请帮我解决。

# rspec 输出错误
Failures:
  1) CommonLog log_error
     Failure/Error: log_error("xxx")
     NameError:
       undefined local variable or method `params' for #<RSpec::Core::ExampleGroup::Nested_1:0x3196f
50>
     # ./lib/common/common_log.rb:3:in `log_error'
     # ./spec/lib/common/common_log_spec.rb:6:in `block (2 levels) in <top (required)>'
# 我的模块文件 common_log.rb
module CommonLog
  def log_error(msg)
    Rails.logger.error "E: controller : #{params[:controller]}  action : #{params[:action]} msg=#{msg}"
  end
end
# 我的规范文件
require 'spec_helper'
require File.expand_path("../../../../lib/common/common_log", __FILE__)
include CommonLog
describe CommonLog do
  it "log_error" do
    log_error("xxx")
  end
end

【问题讨论】:

    标签: ruby-on-rails rspec


    【解决方案1】:

    您必须使用RSpec's anonymous controller 功能。

      require 'spec_helper'
      require File.expand_path("../../../../lib/common/common_log", __FILE__)
    
      describe CommonLog, type: :controller do
    
    
      controller do
        include CommonLog
        def index
           render nothing: true
        end
      end
    
      it "log_error" do
        params = {param1: :value1}
        get :index, params
        #Do the specs you want here
      end
    end
    

    您在这里所做的是创建一个匿名控制器,其中包含您要指定的模块。 由于该模块旨在包含在 rails 控制器中,因此它可以为您提供您所需要的:控制器的上下文来指定您的模块。

    【讨论】:

    • 很高兴看到您的帮助。这个模块在 rails 控制器里面。在你的建议下,我达到了我的目标。匿名控制器的 Rspec 文档对我很有用。非常感谢您的好意。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-23
    • 1970-01-01
    • 1970-01-01
    • 2010-10-23
    相关资源
    最近更新 更多