如何在 RSpec 中包含 Rails Helpers [英] How to include Rails Helpers on RSpec

查看:18
本文介绍了如何在 RSpec 中包含 Rails Helpers的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我做了什么:

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

created a support/helpers.rb file under my spec folder.

support/helpers.rb

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

并试图在 spec_helper.rb 中要求这个文件.

and tried to require this file in 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 中可用?

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

谢谢.

推荐答案

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

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

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 参数来缩小范围:

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

config.include MyControllerHelper, :type => :controller

这篇关于如何在 RSpec 中包含 Rails Helpers的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆