选中框与Capybara有一些选项

时间:2011-03-22 16:46:44

标签: ruby-on-rails selenium cucumber capybara

如何使用Capybara检查选择框是否将某些值列为选项? 它必须与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"

5 个答案:

答案 0 :(得分:61)

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

答案 1 :(得分:22)

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

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

要回答你的问题,这里是实现这个(未经测试)的RSpec代码:

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

如果要测试选项文本而不是值属性(可能适用于more readable场景),可以写:

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

答案 2 :(得分:11)

好吧,因为我在身边,看到了问题(并且今天进行了测试)决定发布我的方式:

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

答案 3 :(得分:11)

作为替代解决方案,并且由于我不熟悉xpath,我这样做是为了解决类似的问题:

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

它非常简单,但花了我一些时间才弄明白。

答案 4 :(得分:3)

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

应该做的伎俩