2013-01-18 50 views

回答

23

你只需要包括相關的輔助模塊測試,以使可用的方法:

describe "foo" do 
    include ActionView::Helpers 

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

這真是那樣簡單。

+0

你能告訴如何調用該方法嗎? 我已經嘗試過'SearchHelper :: formatResultDate(r.date)'和'formatResultDate(r.date)',但又得到另一個「未定義的方法」。 Thks –

+1

是你自己的幫手嗎? SearchHelper是一個模塊嗎?如果是這樣,只需用'include SearchHelper'替換'inlucde ActionView :: Helpers',然後你就可以用'formatResultDate(r.date)'調用該方法。 –

+2

測試郵件程序時,這並不適用於我。例如'expect(mail.body).to match(I18n.t('some.path',argument:link_to(value,custom_url_helper(value)))' –

-1

我假設你正在測試輔助方法。爲了做到這一點,你必須把你的spec文件放入spec/helpers/。鑑於您使用的是rspec-rails寶石,這將爲您提供一個helper方法,允許您調用任何輔助方法。

有在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 
+0

Nop,有很多關於測試助手方法的答案。我正在嘗試在集成測試中使用輔助方法。 Tks無論如何 –

+1

噢好吧。如果你可以擴展你的問題並給出更多的細節(也許一些代碼示例),我會盡力幫助你:) –

4

如果你想使用一個輔助方法對你的看法測試,你可以用下面去:

before do 
    view.extend MyHelper 
end 

它必須是一個describe塊內。

它爲我在軌道上3.2和RSpec 2.13

+0

如果我們假設你在spec/helpers/my_helper_spec .rb從哪裏來的「視圖」在spec? –

+0

@IvailoBardarov對不起,這是爲了使用內部視圖。作爲OP sais:'爲了澄清,我沒有試圖測試一個輔助方法。 – fotanus

8

對於任何人遲到了這個問題,它回答的Relish網站。

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 
0

正如你可以在這裏看到https://github.com/rspec/rspec-rails,你應該初始化與投機/目錄(其中規格將駐留):

$ rails generate rspec:install 

這將產生一個rails_helper.rb與選項

config.infer_spec_type_from_file_location! 

最後需要在你的helper_spec.rb中添加新的rails_helper,而不是需要'spec_helper'。

require 'rails_helper' 
describe ApplicationHelper do 
    ... 
end 

祝你好運。

相關問題