Search code examples
ruby-on-railsrspeccapybarapresenter

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?


Solution

  • 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') }