Cucumber / Capybara:无法选中复选框(按ID,标签,值等)

时间:2015-04-17 02:10:17

标签: ruby-on-rails ruby checkbox cucumber capybara

目前,这是我视图中的代码:

<!-- Renders selected categories as a hash: {"1"=>"Sports", "3"=>"Fashion", "4"=>"World"} -->

  <% unless @categories.nil? %>
    <% @categories.each do |t| %>
      <%= t.name %>
      <%= check_box_tag "categories[#{t.id}]", t.name %>

      <br />
    <% end %>
  <% end %>

这是在浏览器上呈现的,网页上的相应元素如下:

  Entertainment
  <input id="categories_6" name="categories[6]" type="checkbox" value="Entertainment" />

  <br />
  Health
  <input id="categories_5" name="categories[5]" type="checkbox" value="Health" />

  <br />
  Politics
  <input id="categories_3" name="categories[3]" type="checkbox" value="Politics" />

  <br />
  Sports
  <input id="categories_8" name="categories[8]" type="checkbox" value="Sports" />

  <br />
  Tech
  <input id="categories_4" name="categories[4]" type="checkbox" value="Tech" />

  <br />
  Travel
  <input id="categories_7" name="categories[7]" type="checkbox" value="Travel" />

  <br />
  United States
  <input id="categories_1" name="categories[1]" type="checkbox" value="United States" />

  <br />
  World
  <input id="categories_2" name="categories[2]" type="checkbox" value="World" />

  <br />

在我的Cucumber测试中,我希望能够检查我列出的类别,因此我有以下情况/步骤:

步骤:

When /^(?:|I )check "([^"]*)"$/ do |field|
  check(field)
end

情景:

@javascript 
Scenario: a signed in user can post an article with an associated category
  Then I should see "Sign out"
  Then I should see "New Article"
  Then I should see "Hello"
  When I follow "New Article"
  And I fill in "Url" with "Hello_World_Article_URL.com"
  And I fill in "Initial comment" with "My first comment"
  And I check "categories_6"
  And I press "Create Article"
  Then I should see "Article created!"
  Then article url "Hello_World_Article_URL.com" should exist

然而,这在And I check "categories_6"步骤失败,报告了Capybara ElementNotFound错误。我不清楚为什么引用复选框&#34; id&#34;没有正常工作。有没有人能够深入了解我可能做错了什么或者如何解决这个问题?

感谢。

1 个答案:

答案 0 :(得分:0)

制作web_steps,其中包含您要测试的元素的HTML ID。使用Capybara find方法在页面上找到元素。不要忘记将“#”添加到find参数中,以便找到id。然后使用be_checked匹配器,就像这样,

Then /^checkbox "([^"]*)" should be unchecked$/ do |id|
  expect(find("##{id}")).not_to be_checked
end

Then /^checkbox "([^"]*)" should be checked$/ do |id|
  expect(find("##{id}")).to be_checked
end

在场景中使用它们时,只需传入id。

Then checkbox "categories_6" should be unchecked