简体   繁体   中英

How to use Capybara Rspec Matchers to test a presenter?

I'm trying to test a presenter method using a Capybara RSpec matcher.

Lets say I have a method that renders a button. This would be the test I would write if I wasn't using capybara rspec matchers:

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

Using capybara rspec matchers, I want to do this:

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

This approach was proposed in this article http://devblog.avdi.org/2011/09/06/making-a-mockery-of-tdd/ . In the article, the author explains it like this: "I decided to change up my spec setup a bit in order to pass in a template object which included the actual Rails tag helpers. Then I included the Capybara spec matchers for making assertions about HTML."

However, I don't understand this. How can you use capybara rspec matchers when render_controls only returns a content_tag?

Even though luacassus's answer is correct, I found what the problem was. I wasn't including capybara rspec matchers in the test. If you don't include Capybara rspec matchers, you will an error like this: undefined method has_selector? for ActiveSupport::SafeBuffer:0x9449590 .

When you include the rspec matchers, there is no need to use Capybara String method, since rspec matchers match against a string already.

I leave here a more detailed example.

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

Check out Capybara.string method: http://rubydoc.info/github/jnicklas/capybara/master/Capybara#string-class_method

With this method you should be able to write something like that:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM