简体   繁体   English

如何在控制器导轨外部使用Rails参数进行测试

[英]How can I test using rails params outside controller rails

I made a module in /rails_root/lib/common/common_log.rb and included it in ApplicationController, calling it from my controller is normally end. 我在/rails_root/lib/common/common_log.rb中创建了一个模块,并将其包含在ApplicationController中,从我的控制器中调用它通常已结束。 then I did rspec. 然后我做了rspec。 but there was an error. 但出现错误。 I can't understand how do I write params in spec file. 我不明白如何在规范文件中编写参数。 Please help me to solve it. 请帮我解决。

# rspec put out error #rspec发出错误
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
# my module file common_log.rb #我的模块文件common_log.rb
 module CommonLog def log_error(msg) Rails.logger.error "E: controller : #{params[:controller]} action : #{params[:action]} msg=#{msg}" end end 
# my spec file #我的规格文件
 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 

You will have to use RSpec's anonymous controller feature. 您将必须使用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

What you are doing here is creating an anonymous controller which includes the module you want to spec. 您在这里正在创建一个匿名控制器,其中包括您要指定的模块。 Since this module is meant to be included inside a rails controller it gives you exactly what you need: a context of controller to spec your module with. 由于该模块打算包含在rails控制器中,因此它可以为您提供所需的确切信息:一个用于指定模块的控制器上下文。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM