Capybara mini-abstractions

Written . Tagged Capybara, Testing.

Here’s a trick I use in my Capybara tests.

Instead of something like this:

1
2
3
4
5
6
7
8
9
describe "My page" do
  it "lists the item" do
    item = create_item

    within(".test-item-#{item.id}") do
      expect(page).to have_content(item.title)
    end
  end
end

I might do this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
describe "My page" do
  it "lists the item" do
    item = create_item

    within_item_row(item) do
      expect(page).to mention_item(item)
    end
  end

  private

  def within_item_row(item, &block)
    within(".test-item-#{item.id}", &block)
  end

  def mention_item(item)
    have_content(item.title)
  end
end

The private is mostly there as a visual separator; whether the methods are public or private isn’t a practical concern.