Ruby on rails 如何在控制器rails外部使用rails参数进行测试
我在/rails\u root/lib/common/common\u log.rb中创建了一个模块Ruby on rails 如何在控制器rails外部使用rails参数进行测试,ruby-on-rails,rspec,Ruby On Rails,Rspec,我在/rails\u root/lib/common/common\u log.rb中创建了一个模块 module CommonLog def log_error(msg) Rails.logger.error "E: controller : #{params[:controller]} action : #{params[:action]} msg=#{msg}" end end 并将其包含在ApplicationController中, 从我的控制器调用它通常是结束。
module CommonLog
def log_error(msg)
Rails.logger.error "E: controller : #{params[:controller]} action : #{params[:action]} msg=#{msg}"
end
end
并将其包含在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)>'
#我的规范文件
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
您必须使用该功能
您在这里所做的是创建一个匿名控制器,其中包括您想要规范的模块。
由于此模块将包含在rails控制器中,因此它为您提供了所需的内容:控制器的上下文以规范您的模块。我很高兴看到您的帮助。该模块位于rails控制器内部。你的建议使我达到了目标。匿名用户控制器的Rspec文件对我有用。非常感谢你的好意。
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