1

on my index page I have this div:

<div class="banner">
  <h1 class="glow-header">Galaxy Far, Far Away? Quick Trip to Mars?<br>
    Pianeta has you covered.</h1>
<div>

In my testfile this works:

RSpec.describe 'home features' do
  it 'displays the name of the app and links to the index-all planets page' do
    visit root_path
    expect(page).to have_content('Space is full of surprises.')
    click_link('Go Beyond')
    expect(current_path).to eq('/planets')
    expect(page).to have_content('Galaxy Far, Far Away?')
  end
end

But I would like it to be working with the h1 included. I did this:

expect(page).to have_content('<h1 class="glow-header">Galaxy Far, Far Away? Quick Trip to Mars?<br>
    Pianeta has you covered.</h1>')
end

But the test failed. What did I do wrong ?

Anna
  • 113
  • 1
  • 7

2 Answers2

0

The #has_content?/#has_text? method only checks the text content of the page. It does not look at the HTML tags.

If you want to check for content within a specific HTML element there is a #within method that takes a block and will scope the Capybara lookups within it to be within the matched element. The element referenced by #within must exist or Capybara will raise an exception.

page.within('h1.glow-header') do
  expect(page).to have_content('Galaxy Far, Far Away?')
end
patrickmcgraw
  • 2,465
  • 14
  • 8
  • Yup, you might also want to add an ID or something to the HTML tag, as the class name is very generic and the code will break if you use it twice on the page. – TTD Jul 27 '21 at 21:44
0

If you don't want to deal with scoping using within for a single expectation you could do

expect(page).to have_css('h1.glow-header', text: 'Galaxy Far, Far Away?')

If you've already got a reference to the header you could also do something like

header = find('h1.glow-header')
...
expect(header).to have_text('Galaxy Far, Far Away?')

Additionally you should not be doing expect(current_path).to eq('/planets'). Using RSpecs eq matcher with Capybara will lead to flaky tests as soon as you move to using an asynchronous (JS supporting) driver, because it prevents Capybaras auto waiting/retrying behaviors. Instead you should use the Capybara provided matcher

expect(page).to have_current_path('/planets')
Thomas Walpole
  • 48,548
  • 5
  • 64
  • 78