49

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.

Kleber S.
  • 8,110
  • 6
  • 43
  • 69

3 Answers3

42

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
Brandan
  • 14,735
  • 3
  • 56
  • 71
  • 1
    Note for an edge case: this code will be problematic in testing a Rails Engine, where you would start from `File.dirname(__FILE__)` instead of `Rails.root` since they will differ. – Joe Atzberger Jun 15 '16 at 23:05
  • 1
    FYI this is include (but commented out) in the `/spec/rails_helpers.rb` file in 5.0.1. – Jay Killeen Jan 04 '17 at 23:04
31

Include the Module you need directly in the spec file:

include PostsHelper
originalhat
  • 1,676
  • 16
  • 18
0

(Rails 7) You can also extend the helpers lookup location in e.g. application.rb like

# https://guides.rubyonrails.org/configuring.html#configuring-action-view
config.helpers_paths << 'path/to/unusual/helper/location.rb'
Felix
  • 4,510
  • 2
  • 31
  • 46