Ruby-on-rails 如何在 RSpec 上包含 Rails Helpers

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9445410/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 02:54:38  来源:igfitidea点击:

How to include Rails Helpers on RSpec

ruby-on-railsruby-on-rails-3rspectddrspec2

提问by Kleber S.

I'm trying to include some helpers to test with rspec but no luck.

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

What I did:

我做了什么:

created a support/helpers.rbfile under my specfolder.

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

support/helpers.rb

支持/helpers.rb

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

and tried to require this file in spec_helper.rb.

并试图在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

this generates the following error:

这会产生以下错误:

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

How should I do this helpers to be available with Rspec?

我应该如何做这个助手才能与 Rspec 一起使用?

Thanks.

谢谢。

采纳答案by Brandan

I normally include this code to require everything under my spec/supportsubdirectory once the Rails stack is available:

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

Spork.prefork do

  # ...

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

  RSpec.configure do |config|
    config.include MyCustomHelper

    # ...
  end
end

Note that this will include MyCustomHelperin all example types (controllers, models, views, helpers, etc.). You can narrow that down by passing a :typeparameter:

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

config.include MyControllerHelper, :type => :controller

回答by obfk

Simply include the Module you need directly in the spec file:

只需将您需要的模块直接包含在规范文件中:

include PostsHelper