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

耗尽温柔 提交于 2019-12-20 11:05:27

问题


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.


回答1:


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.




回答2:


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



回答3:


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




回答4:


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.




回答5:


As you can see here https://github.com/rspec/rspec-rails , you should initialize the spec/ directory (where specs will reside) with:

$ rails generate rspec:install

this will generate an rails_helper.rb with the option

config.infer_spec_type_from_file_location!

and finally require the new rails_helper in you helper_spec.rb instead of requiring 'spec_helper'.

require 'rails_helper'
describe ApplicationHelper do
  ...
end

good luck.




回答6:


I'm assuming you're trying to test the helper method. In order to do this you'll have to put your spec file into spec/helpers/. Given you're using the rspec-rails gem, this will provide you a helper method that allows you to call any helper method on it.

There's a nice example over in the official rspec-rails documentation:

require "spec_helper"

describe ApplicationHelper do
  describe "#page_title" do
    it "returns the default title" do
      expect(helper.page_title).to eq("RSpec is your friend")
    end
  end
end


来源:https://stackoverflow.com/questions/14402067/how-to-call-an-app-helper-method-from-an-rspec-test-in-rails

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