0

Using RSpec and Capybara to test for the existence of an element within a div with class 'foo'.

<div class="foo">
  <p>Text zzz</p>
  Looking for element here
</div>
<div class="foo">
  <p>Text aaa</p>
  Element should not exist within this div.
</div>

There are many divs with class 'foo' on the page, and I can give them different ID's based on foo's ID in the database.

But I don't know foo's ID from within the test. And, I don't want to test the parent of the divs because an element should be present in one div and absent in another.

What is the best way to test for an element in this case?

1
  • From the way you've phrased the question, there's no way to determine in which element the content should be. You say you don't have the id of foo in the test environment, but what do you have? Commented Aug 16, 2012 at 0:52

2 Answers 2

2

If I understand the question correctly (and I'm not 100% confident I do), I think this should work:

el1 = find(:xpath, '//div[@class="foo"][./p[contains(.,"Text zzz")]]')
el2 = find(:xpath, '//div[@class="foo"][./p[contains(.,"Text aaa")]]')

There's probably a slightly simpler way to do this using css instead of xpath, but I've found that this works for this type of situation. (Note: I haven't actually tested this code.)

Sign up to request clarification or add additional context in comments.

Comments

1
parent = find("p[text()='zzz']").find(:xpath,"..")
within parent do
  ...

https://github.com/jnicklas/capybara/pull/505

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.