【问题标题】:How to include a support file for rspec如何包含 rspec 的支持文件
【发布时间】:2014-01-04 00:54:54
【问题描述】:

我正在构建一个 rails 4 应用程序。我创建了一个支持文件来模拟登录。这是文件

spec/support/spec_test_helper.rb

module SpecTestHelper
  def login(user)
    request.session[:user_id] = user.id
  end

  def current_user
    User.find(request.session[:user_id])
  end
end

spec_helper.rb

config.include SpecTestHelper, :type => :controller

控制器规格

describe BooksController, "user role" do

  user = Fabricate(:user) do
    role { Role.find_by_account_type("user") }
  end

  login(user)
end

支持文件给出未定义的方法错误。这是错误消息的一部分:

spec/controllers/books_controller_spec.rb:27:in `block in <top (required)>': undefined method `login' for #<Class:0x007f9f83193438> (NoMethodError)

我正在测试 CanCan。我知道测试 CanCan 的正确方法是测试能力,但这已经完成了。

【问题讨论】:

  • 请提供准确的错误信息。

标签: ruby-on-rails rspec rspec-rails


【解决方案1】:

rspec 目录下可以有两个文件:rails_helper.rbspec_helper.rb。如果你想为依赖rails的类提供支持,你应该使用rails_helper告诉rails加载'spec/support'目录下的模块。

Dir[Rails.root.join('spec/support/**/*.rb')].each { |f| require f }

要声明共享模块,您需要在配置块中使用它。

RSpec.configure do |config|
  ...
  config.include <YourModuleName>::<YourClassName>, :type => :controller
  ...
end

但是,如果你的类根本不需要 rails,你可以在spec_helper 下加载它,这样就不会加载 rails 来运行测试。 请参阅this answerthis reference 了解更多信息。

【讨论】:

    【解决方案2】:

    替代@gotva 提供的答案。它略显冗长,但适用于 Rails 3 和 4:

    Dir[File.expand_path(File.join(File.dirname(__FILE__),'support','**','*.rb'))].each {|f| require f} 
    

    【讨论】:

      【解决方案3】:

      我在spec_helper.rb 中添加了这一行,它适用于 3rd Rails

      Dir[Rails.root.join("spec/support/**/*.rb")].each {|f| require f}
      

      也许存在另一个(更漂亮的)解决方案

      【讨论】:

      • 所以请注意@Ash 的回答——您真的应该在其中/之前/让...建立记录和调用方法...
      【解决方案4】:

      login(user) 调用放在beforeit 块中,而不是直接放在describe 中:

      let(:user) do
        Fabricate(:user) do
          role { Role.find_by_account_type("user") }
        end
      end
      
      before do
        login(user)
      end
      

      【讨论】:

      • 是的!非常感谢,这就是问题所在。
      猜你喜欢
      • 1970-01-01
      • 2021-01-16
      • 2012-01-04
      • 2015-09-08
      • 2011-10-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多