Rspec with Capybara has_css doesn't work
In Cucumber, with Rspec and Capybara, I have a test to check that the button has a class. Here
expect(@some_button).to have_css(".in-cart")
it doesn't work but
@some_button['class']
returns
'btn product in-cart'
so the button definitely has the class "in the cart".
As a temporary measure, I changed my test:
expect(@some_button['class']).to match /in-cart/
This is obviously insane. But why has "has_css" or "has_css"? return false for a DOM element that clearly has the expected class?
Also page.all ('. In-cart') includes a button so Capybara can definitely find it.
BTW, I've also tried "button.in-cart", "in-cart", expect (etc). to have_selector, expect (etc. has_selector? ("in the basket")). be_truthy and all combinations.
source to share
have_css
The match is expected to apply to the parent container instead of the actual element
# your view
<div id="container">
<div class="in_cart product"></div>
</div>
# your step definition
parent = page.find('div#container')
expect(parent).to have_css(".in-cart")
# => returns true, as there is nested div.in_cart
expect('div#container div').to have_css(".in-cart")
# => returns false, as there is no such selector inside of the latter div
As with mapping the attributes of an exact object, you should stick with a simple query with a key
element = page.find('div#container div')
element['class'].should include('in-cart')
expect(element['class']).to match /in-cart/
The same logic applies to all RSpecMatchers .
source to share
In newer versions, Capybara / Rspec will, by default, expect(page)
query the entire page that is looking for a match; however, sometimes we may not like it and instead it will target a specific class / area of ββthe page. For these cases, narrow down the context page
with within
:
within('.container') do
expect(page).to have_css(".in-cart")
end
Assuming the parent has a container
Capybara class will only search in that element.
source to share