How to include Rails Helpers on RSpec
Asked Answered
O

3

50

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.

Owen answered 25/2, 2012 at 15:39 Comment(0)
H
43

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
Hohenzollern answered 25/2, 2012 at 16:41 Comment(2)
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.Metheglin
FYI this is include (but commented out) in the /spec/rails_helpers.rb file in 5.0.1.Abortionist
W
32

Include the Module you need directly in the spec file:

include PostsHelper
Wroth answered 14/10, 2013 at 0:30 Comment(3)
ad the beginning of the fileBawdyhouse
Does anyone know how to do this in a view? <% include PostsHelper %> produces the error undefined method include' for #<ActionView::Base:0x0000559478b3cf60>`…Lavalava
thanks to @Bawdyhouse to point out that its important to put it at beginning!Evy
K
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'
Kedron answered 21/2, 2023 at 10:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.