Benito Serna
Ruby, Rails, TDD...

Custom capybara matchers with compound expectations

Imagine that you want to refactor this…

expect(row).to have_css("[data-role=description]", text: "Desc 1")
expect(row).to have_css("[data-role=amount]", text: "$250.00")

into this…

expect(row).to display_entry_with("Desc1", $250.00)

What would you do?…

Maybe you can write a custom matcher, but at least for me, in cases like this, it just feel like too much.

One thing that I think is simpler is to use rspec’s compound expectations, to chain all the expectations that you want, and return a matcher.

Something like this…

def display_entry_with(description, amount)
  have_css("[data-role=description]", text: description)
    .and have_css("[data-role=amount]", text: amount)
end

I have found this little trick very usefull, I hope it can help you too.

Related articles