2012-04-04 99 views
4

我正在嘗試使用Capybara RSpec匹配器來測試演示者方法。如何使用Capybara Rspec Matchers測試主持人?

可以說我有一個呈現按鈕的方法。這將是考驗我,如果我不使用水豚的RSpec匹配器寫:

it "should generate a button" do 
    template.should_receive(:button_to).with("Vote"). 
    and_return("THE_HTML") 
    subject.render_controls.should be == "THE_HTML" 
end 

使用水豚rspec的匹配器,我想這樣做:

it "should render a vote button" do 
    subject.render_controls.should have_button('Vote') 
end 

這種方法是本文提出http://devblog.avdi.org/2011/09/06/making-a-mockery-of-tdd/。在文章中,作者解釋如下:「我決定改變我的規格設置,以便傳入一個模板對象,其中包含實際的Rails標記助手,然後我將Capybara規範匹配器包含在HTML中進行斷言「。

但是,我不明白這一點。當render_controls僅返回content_tag時,如何使用capybara rspec匹配器?

回答

6

即使luacassus的答案是正確的,我發現了什麼問題。在測試中,我不包括水豚rspec匹配者。如果你不包括水豚RSpec匹配器,你會這樣的錯誤:未定義的方法has_selector?對於ActiveSupport :: SafeBuffer:0x9449590

如果包含rspec匹配器,則不需要使用Capybara字符串方法,因爲rspec匹配器已經與字符串匹配。

我在這裏留下一個更詳細的例子。

require_relative '../../app/presenters/some_presenter' 
require 'capybara/rspec' 

describe 'SomePresenter' 
    include Capybara::RSpecMatchers 

    let(:template) { ActionView::Base.new } 
    subject { Presenter.new(template) } 

    it "should render a vote button" do 
    subject.render_controls.should have_button('Vote') 
    end 
end 
相關問題