Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call an app helper method from an RSpec test in Rails?

The title is self explanatory.

Everything I've tried led to a "undefined method".

To clarify, I am not trying to test a helper method. I am trying to use a helper method in an integration test.

like image 561
Helio Santos Avatar asked Jan 18 '13 15:01

Helio Santos


People also ask

How do I run a test in RSpec?

To run a single Rspec test file, you can do: rspec spec/models/your_spec. rb to run the tests in the your_spec. rb file.

Why helper is used in Rails?

Basically helpers in Rails are used to extract complex logic out of the view so that you can organize your code better.

What RSpec method is used to create an example?

The describe Keyword The word describe is an RSpec keyword. It is used to define an “Example Group”. You can think of an “Example Group” as a collection of tests. The describe keyword can take a class name and/or string argument.


4 Answers

You just need to include the relevant helper module in your test to make the methods available:

describe "foo" do
  include ActionView::Helpers

  it "does something with a helper method" do
    # use any helper methods here

It's really as simple as that.

like image 148
Chris Salzberg Avatar answered Sep 21 '22 17:09

Chris Salzberg


For anyone coming late to this question, it is answered on the Relish site.

require "spec_helper"

describe "items/search.html.haml" do
  before do
    controller.singleton_class.class_eval do
      protected
      def current_user
        FactoryGirl.build_stubbed(:merchant)
      end
      helper_method :current_user
    end
  end

  it "renders the not found message when @items is empty" do
    render

    expect(
      rendered
    ).to match("Sorry, we can't find any items matching "".")
  end
end
like image 45
Mark Paine Avatar answered Sep 23 '22 17:09

Mark Paine


If you are trying to use a helper method on your view test, you can go with the following:

before do
  view.extend MyHelper
end

It must be inside a describe block.

It works for me on rails 3.2 and rspec 2.13

like image 4
fotanus Avatar answered Sep 23 '22 17:09

fotanus


Based on Thomas Riboulet's post on Coderwall:

At the beginning of your spec file add this:

def helper
  Helper.instance
end

class Helper
  include Singleton
  include ActionView::Helpers::NumberHelper
end

and then call a particular helper with helper.name_of_the_helper.

This particular example includes the ActionView's NumberHelper. I needed the UrlHelper, so I did include ActionView::Helpers::UrlHelper and helper.link_to.

like image 2
Alexander Popov Avatar answered Sep 24 '22 17:09

Alexander Popov