Ruby-on-rails Capybara,在 css 元素中查找
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8158328/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Capybara, finding within a css element
提问by ardavis
I'm working with Ruby on Rails 3, Cucumber, and Capybara
我正在使用 Ruby on Rails 3、Cucumber 和 Capybara
I've been searching for quite some time, and I can't figure out how to find a specific page element within a css tag. In my case, I need to make sure that a name is found inside of a table, and not in the "Welcome [Name]".
我已经搜索了很长时间,但我不知道如何在 css 标签中找到特定的页面元素。就我而言,我需要确保在表中找到名称,而不是在“欢迎 [姓名]”中。
I tried something like:
我试过类似的东西:
within('table') do
page.body.index("[Name]")
end
And I have a table with id='table'.
我有一张桌子id='table'。
But I'd like to know how to do this for any css element, such as:
但我想知道如何对任何 css 元素执行此操作,例如:
within('h2') do
page.body.should have_content ('stuff')
end
I think my problem has to do with page.body, but I'm not sure how to contain it to a particular css tag.
我认为我的问题与 page.body 有关,但我不确定如何将它包含到特定的 css 标签中。
Thanks in advance!
提前致谢!
回答by Dylan Markow
Capybara's withinmatcher only matches the first result, so if you have multiple h2tags, it'll only look in the first one.
Capybara 的within匹配器只匹配第一个结果,所以如果你有多个h2标签,它只会查找第一个。
Instead, try have_csswith the :textoption.
相反,请尝试have_css使用该:text选项。
page.should have_css("#table", :text => "[Name]")
page.should have_css('h2', :text => 'stuff')
回答by Paul Groves
To find a specific element:
要查找特定元素:
page.find('#table').should have_text('stuff')
回答by Jo?o Vitor
I guess all answers should work but now Capybara doesn't use should anymore it uses expect
我想所有的答案都应该有效,但现在 Capybara 不再使用 should 了,它使用 expect
expect(page).to have_css("#table", :text => "[Name]")
expect(page).to have_css('h2', :text => 'stuff')
回答by Hymanlin
I've done stuff like this:
page.all(:css, 'button.btn-primary.days.active').size.should == 1
我做过这样的事情:
page.all(:css, 'button.btn-primary.days.active').size.should == 1
To check if there are any elements that contain a specific set of classes.
I didn't need to look for a particular text value of the element though.
I just wanted to ensure the existence of the element, and how many of them there were.
检查是否有任何包含特定类集的元素。
不过,我不需要查找元素的特定文本值。我只是想确保元素的存在,以及有多少元素。

