How to check if text appears on page in rails functional test?
Asked Answered
S

3

6

I am currently writing functional tests for my controller, and I want to check if a line

This is a test line

appears on my page.

I tried using

assert_select "p" do
  assert_select "this is the test line"
end

but i think something is wrong with this line.

What is the best way to do this in rails version 3?

Storekeeper answered 1/7, 2013 at 20:6 Comment(1)
Please do not keep updating the code in your question -- it makes the Q&A format fall apart.Einsteinium
E
6

I think you're just looking for:

assert_select "p", "this is the test line"

See the docs for more info about assert_select.

Note that the line above depends on the text being wrapped in a <p> tag, and being a literal match. If it's in another tag, you'll need to specify the correct selector. If you'd like to match on a Regex, that is also supported, via:

assert_select "p", /test line/

Note that this will not be very performant, as it will scan through all <p>'s in your document. Consider a more tightly specified selector, like a class or ID on the element you're targeting.

Einsteinium answered 1/7, 2013 at 20:11 Comment(2)
I think my problem is that this p is inside a bunch of divs, for example <div><div><div><p> this is a test line</p></div></div></div>. Does this mean i have to specify that in the tag? Like div.div.div.p?Storekeeper
So i found the answer, i added a class to the p and in assert_select did p.class and then "string" worked like a charm.Storekeeper
M
15

Without specifying a tag:

assert_match "this is the test line", response.body
Manlove answered 5/10, 2017 at 23:43 Comment(0)
E
6

I think you're just looking for:

assert_select "p", "this is the test line"

See the docs for more info about assert_select.

Note that the line above depends on the text being wrapped in a <p> tag, and being a literal match. If it's in another tag, you'll need to specify the correct selector. If you'd like to match on a Regex, that is also supported, via:

assert_select "p", /test line/

Note that this will not be very performant, as it will scan through all <p>'s in your document. Consider a more tightly specified selector, like a class or ID on the element you're targeting.

Einsteinium answered 1/7, 2013 at 20:11 Comment(2)
I think my problem is that this p is inside a bunch of divs, for example <div><div><div><p> this is a test line</p></div></div></div>. Does this mean i have to specify that in the tag? Like div.div.div.p?Storekeeper
So i found the answer, i added a class to the p and in assert_select did p.class and then "string" worked like a charm.Storekeeper
C
0

this works with rails 6:

assert_selector "p", text: "this is the test line"

doc: https://www.rubydoc.info/github/jnicklas/capybara/Capybara/Node/Matchers

(I was getting Unused parameters passed to Capybara::Queries::SelectorQuery)

Choral answered 4/5, 2019 at 14:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.