检查select框与水豚有一定的select

如何使用Capybara来检查select框是否具有列为选项的某些值? 它必须与Selenium兼容…

这是我有的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> 

这是我想要做的:

 Then the "cars" field should contain the option "audi" 

尝试使用capybara 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 

对于它的价值,我会把它称为下拉菜单,而不是字段,所以我会写:

 Then the "cars" drop-down should contain the option "audi" 

要回答你的问题,下面是RSpec代码来实现这个(未经testing):

 Then /^the "([^"]*)" drop-down should contain the option "([^"]*)"$/ do |id, value| page.should have_xpath "//select[@id = '#{id}']/option[@value = '#{value}']" end 

如果你想testing选项文本而不是值属性(这可能会使更多的可读scheme),你可以写:

  page.should have_xpath "//select[@id = '#{id}']/option[text() = '#{value}']" 

那么,因为我在附近,看到这个问题(并在今天进行testing)决定张贴我的方式:

 within("select#cars") do %w(volvo saab mercedes audi).each do |option| expect(find("option[value=#{option}]").text).to eq(option.capitalize) end end 

作为一种替代解决scheme,由于我对xpaths不熟悉,所以我这样做来解决类似的问题:

 page.all('select#cars option').map(&:value).should == %w(volvo saab mercedes audi) 

它很简单,但花了我一些时间来弄清楚。

 Then I should see "audi" within "#cars" 

应该做的伎俩