【问题标题】:Cucumber/Capybara : Cannot check a checkbox (by id, label, value, etc)Cucumber/Capybara:无法选中复选框(通过 id、标签、值等)
【发布时间】:2015-04-17 02:10:17
【问题描述】:

目前,这是我认为的代码:

<!-- 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 错误。我不清楚为什么通过“id”引用复选框不能正常工作。有没有人了解我可能做错了什么或者我可以如何解决这个问题?

谢谢。

【问题讨论】:

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


    【解决方案1】:

    使用您要测试的元素的 HTML id 制作 web_steps。使用 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多