19
votes

Given I have a full_title method in ApplicationHelper module, how can I access it in a RSpec request spec?

I have the following code now:

app/helpers/application_helper.rb

    module ApplicationHelper

    # Returns the full title on a per-page basis.
    def full_title(page_title)
      base_title = "My Site title"
      logger.debug "page_title: #{page_title}"
      if page_title.empty?
         base_title
      else
        "#{page_title} - #{base_title}"
      end
    end

spec/requests/user_pages_spec.rb

   require 'spec_helper'

   describe "User Pages" do
      subject { page }

      describe "signup page" do 
          before { visit signup_path }

          it { should have_selector('h2', text: 'Sign up') } 
          it { should have_selector('title', text: full_title('Sign Up')) } 

      end
    end

On running this spec, I get this error message:

NoMethodError: undefined method full_title' for #<RSpec::Core::ExampleGroup::Nested_1::Nested_1:0x00000003d43138>

As per the tests in Michael Hartl's Rails Tutorial, I should be able to access the application helper methods in my user spec. What mistake am I making here?

3
I have the exact same code and it works for me. Can you add more information to your error message? Also, do you have a github repo you can share? - Paul Fioravanti
Have you created your utilities.rb file with the helper, in your spec/support directory? - veritas1
I checked out your code and all specs passed. Did you migrate your database and not restart spork? - Paul Fioravanti
Then see listing 5.26 in your book. That is how the author has the helper made available in rspec. Rspec will auto load files in spec/support. - veritas1
@veritas1 Ok, I oversaw that listing. Thanks a lot. Can you add this as an answer, so I can accept it? - rohitmishra

3 Answers

40
votes

Another option is to include it directly in the spec_helper

RSpec.configure do |config|
  ...
  config.include ApplicationHelper
end
10
votes

I am doing Ruby on Rails Tutorial (Rails 4.0 version) using currently-latest versions of each gem. I experienced a similar problem wondering how to include the ApplicationHelper to the specs. I got it working with following code:

spec/rails_helper.rb

RSpec.configure do |config|
  ...
  config.include ApplicationHelper
end

spec/requests/user_pages_spec.rb

require 'rails_helper'

describe "User pages", type: :feature do
  subject { page }

  describe "signup page" do 
    before { visit signup_path }

    it { is_expected.to have_selector('h2', text: 'Sign up') } 
    it { is_expected.to have_selector('title', text: full_title('Sign Up')) } 
  end
end

Gemfile

...
# ruby 2.2.1
gem 'rails', '4.2.1'
...
group :development, :test do
  gem 'rspec-rails', '~> 3.2.1' 
  ...
end

group :test do
  gem 'capybara', '~> 2.4.4'
  ...
1
votes

Create the helper in spec/support/utilities.rb as per listing 5.26 of the book.