Ruby-on-rails 选中选择框对 Capybara 具有某些选项
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5394799/
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
Check select box has certain options with Capybara
提问by Tom Maeckelberghe
How do I use Capybara to check that a select box has certain values listed as options? It has to be compatible with Selenium...
如何使用 Capybara 检查选择框是否将某些值列为选项?它必须与硒兼容...
This is the HTML that I have:
这是我拥有的 HTML:
<select id="cars">
<option></option>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
This is what I want to do:
这就是我想要做的:
Then the "cars" field should contain the option "audi"
回答by Jeff Perrin
Try using the capybara rspec matcher have_select(locator, options = {})instead:
尝试使用水豚 rspec 匹配器have_select(locator, options = {})代替:
#Find a select box by (label) name or id and assert the given text is selected
Then /^"([^"]*)" should be selected for "([^"]*)"$/ do |selected_text, dropdown|
expect(page).to have_select(dropdown, :selected => selected_text)
end
#Find a select box by (label) name or id and assert the expected option is present
Then /^"([^"]*)" should contain "([^"]*)"$/ do |dropdown, text|
expect(page).to have_select(dropdown, :options => [text])
end
回答by Jo Liss
For what it's worth, I'd call it a drop-down menu, not a field, so I'd write:
就其价值而言,我将其称为下拉菜单,而不是字段,因此我会这样写:
Then the "cars" drop-down should contain the option "audi"
To answer your question, here's the RSpec code to implement this (untested):
要回答您的问题,这是实现此功能的 RSpec 代码(未经测试):
Then /^the "([^"]*)" drop-down should contain the option "([^"]*)"$/ do |id, value|
page.should have_xpath "//select[@id = '#{id}']/option[@value = '#{value}']"
end
If you want to test for the option text instead of the value attribute (which might make for more readablescenarios), you could write:
如果要测试选项文本而不是 value 属性(这可能会使场景更具可读性),您可以编写:
page.should have_xpath "//select[@id = '#{id}']/option[text() = '#{value}']"
回答by Mauricio Moraes
As an alternative solution, and as I'm not familiar with xpaths, I did this to solve a similar problem:
作为替代解决方案,由于我不熟悉 xpaths,我这样做是为了解决类似的问题:
page.all('select#cars option').map(&:value).should == %w(volvo saab mercedes audi)
Its quite simple, but took me some time to figure out.
它很简单,但我花了一些时间才弄明白。
回答by Daniel
Well, since i was around and saw the question (and been testing today) decided to post my way:
好吧,因为我在附近看到了这个问题(今天一直在测试)决定发布我的方式:
within("select#cars") do
%w(volvo saab mercedes audi).each do |option|
expect(find("option[value=#{option}]").text).to eq(option.capitalize)
end
end
回答by corroded
Then I should see "audi" within "#cars"
should do the trick
应该做的伎俩

