【问题标题】:How to use Capybara Rspec Matchers to test a presenter?如何使用 Capybara Rspec Matchers 测试演示者?
【发布时间】:2012-04-18 13:31:57
【问题描述】:

我正在尝试使用 Capybara RSpec 匹配器测试演示者方法。

假设我有一个呈现按钮的方法。如果我不使用 capybara 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

使用 capybara 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 匹配器?

【问题讨论】:

    标签: ruby-on-rails rspec capybara presenter


    【解决方案1】:

    尽管 luacassus 的回答是正确的,但我还是发现了问题所在。我没有在测试中包括 capybara rspec 匹配器。如果你不包含 Capybara rspec 匹配器,你会出现这样的错误:undefined method has_selector?对于 ActiveSupport::SafeBuffer:0x9449590

    当您包含 rspec 匹配器时,无需使用 Capybara String 方法,因为 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
    

    【讨论】:

      【解决方案2】:

      查看Capybara.string方法:http://rubydoc.info/github/jnicklas/capybara/master/Capybara#string-class_method

      用这个方法你应该可以写出类似的东西:

      subject { Capybara.string(presenter.render_controls }
      it { should have_button('Vote') }
      

      【讨论】:

        猜你喜欢
        • 2016-06-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-04-05
        • 2019-09-27
        • 2012-06-12
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多