How to include Rails Helpers on RSpec

不想你离开。 提交于 2019-11-27 11:29:22

问题


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

What I did:

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

support/helpers.rb

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

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

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?

Thanks.


回答1:


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

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



回答2:


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

include PostsHelper


来源:https://stackoverflow.com/questions/9445410/how-to-include-rails-helpers-on-rspec

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!