Benito Serna Tips and tools for Ruby on Rails developers

Custom capybara matchers with compound expectations

March 17, 2021

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

Subscribe to get future posts via email

Here I try to share knowledge and fixes to common problems and struggles for ruby on rails developers, like How to fetch the latest-N-of-each record or How to test that an specific mail was sent or a Capybara cheatsheet. You can see more examples on Most recent posts or all posts.