Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 238
e3matheus Avatar asked Dec 20 '22 23:12

e3matheus


1 Answers

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
like image 152
e3matheus Avatar answered Dec 30 '22 06:12

e3matheus