0

我在 /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
4

1 回答 1

0

您将不得不使用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

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

于 2013-06-15T08:27:31.607 回答