Skip to content

Instantly share code, notes, and snippets.

@dogweather
Last active May 15, 2024 05:31
Show Gist options
  • Save dogweather/b9a5c7d27792b77677e27747acf3d2f4 to your computer and use it in GitHub Desktop.
Save dogweather/b9a5c7d27792b77677e27747acf3d2f4 to your computer and use it in GitHub Desktop.
Use CSS Selectors in RSpec Request Specs
def css(selector)
html.css(selector).text
end
def html
Nokogiri::HTML(response.body)
end
# How to use the above helpers.
RSpec.describe 'Test some page', type: :request do
it 'has a <p> with "Title"' do
get '/my-page'
expect( css 'p' ).to include 'Title'
end
end
@woto
Copy link

woto commented May 14, 2024

How about:

  include Capybara::RSpecMatchers

and then

expect(response.body).to have_text('...')

@dogweather
Copy link
Author

How would you check if there's a <p> with the text Title?

@woto
Copy link

woto commented May 14, 2024

I believe this will work:

expect(response.body).to have_css('p', text: 'Title')

https://rubydoc.info/github/jnicklas/capybara/Capybara/Node/Matchers#has_css%3F-instance_method

To be honest, I didn't know about the feature of using capybara selectors with requests tests. Just found this way after I found your solution. Just wanted to share with you :)

ps.

But in same time I knew about feature:

visit ...
expect(page).to ....

But with rack instead of headless browsers. But I like my proposed solution more without all the rspec tags like tag: :js, you know...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment