【问题标题】:How to include Rails Helpers on RSpec如何在 RSpec 中包含 Rails 助手
【发布时间】:2012-02-25 15:39:14
【问题描述】:

我正在尝试包含一些帮助程序来使用 rspec 进行测试,但没有运气。

我做了什么:

在我的spec 文件夹下创建了一个support/helpers.rb 文件。

support/helpers.rb

module Helpers
  include ActionView::Helpers::NumberHelper
  include ActionView::Helpers::TextHelper
end

并尝试在spec_helper.rb 中要求此文件。

# This file is copied to spec/ when you run 'rails generate rspec:install'
require 'rubygems'
require 'spork'
require 'support/helpers'

Spork.prefork do
.
.
end

这会产生以下错误:

/spec/support/helpers.rb:2:in `<module:Helpers>': uninitialized constant Helpers::ActionView (NameError)

我应该如何使用 Rspec 来使用这些帮助程序?

谢谢。

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 rspec tdd rspec2


    【解决方案1】:

    一旦 Rails 堆栈可用,我通常会包含此代码以要求 spec/support 子目录下的所有内容:

    Spork.prefork do
    
      # ...
    
      Dir[Rails.root.join('spec', 'support', '**', '*.rb')].each { |f| require f }
    
      RSpec.configure do |config|
        config.include MyCustomHelper
    
        # ...
      end
    end
    

    请注意,这将在所有示例类型(控制器、模型、视图、帮助器等)中包括 MyCustomHelper。您可以通过传递 :type 参数来缩小范围:

    config.include MyControllerHelper, :type => :controller
    

    【讨论】:

    • 注意极端情况:此代码在测试 Rails 引擎时会出现问题,您将从 File.dirname(__FILE__) 而不是 Rails.root 开始,因为它们会有所不同。
    • 仅供参考,这是在 5.0.1 的 /spec/rails_helpers.rb 文件中包含(但已注释掉)。
    【解决方案2】:

    在spec文件中直接包含你需要的模块:

    include PostsHelper
    

    【讨论】:

    • 在文件开头添加广告
    • 有谁知道如何在视图中执行此操作? &lt;% include PostsHelper %&gt; 为 #<:base:0x0000559478b3cf60> 生成错误 undefined method include'...
    猜你喜欢
    • 1970-01-01
    • 2020-04-24
    • 1970-01-01
    • 1970-01-01
    • 2020-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-04
    相关资源
    最近更新 更多