代码之家  ›  专栏  ›  技术社区  ›  Nathan Long

黄瓜:找到标签文本X的输入?

  •  5
  • Nathan Long  · 技术社区  · 15 年前

    在Cucumber中,我试图创建这样一个步骤:

    Then I should see "Example business name" in the "Business name" input
    

    我希望“Business name”输入定义为“标签上有文本“Business name”的输入”

    到目前为止,我的步骤如下:

    Then /^I should see "([^"]*)" in the "([^"]*)" input$/ do |content, labeltext|
      # Not sure what to put here
    end
    

    在jQuery中,我会查找带有该文本的标签,查看其“for”属性,并找到具有该I d的输入

    within("input:nth-child(#{pos.to_i}")
    

    page.should have_content('foo')
    

    有谁能推荐使用Webrat/Capybara选择器语法的解决方案吗?

    2 回复  |  直到 15 年前
        1
  •  11
  •   Nathan Long    15 年前

    明白了

    您可以使用 find_field(labeltext) .

    # Example:
    # 'I should see "Howdy" in the "Greeting" input' ("Greeting" is the label text)
    Then /^I should see "([^"]*)" in the "([^"]*)" input$/ do |content, labeltext|
        find_field("#{labeltext}").value.should == content
    end
    
        2
  •  0
  •   Pietro Polsinelli    15 年前

    这也行。这里的区别在于,它根据标签文本的部分匹配来查找字段。我们的字段有一个“:”结尾处,但它并不总是正确的,所以我不想匹配整个标签值。。。

    When /^i enter "([^"]*)" in the "([^"]*)" field$/i do |value, fieldname|
      @thefield = all("label").detect { |l| l.has_content?(fieldname) }
      if @thefield.nil? then
        raise Exception.new("Couldn't find field #{fieldname}")
      end
      fill_in @thefield[:for], :with=>value
    end
    

    不过,我还是想把这个扩展到不区分大小写。 这是我第一天使用rspec,cucumber,我真的从来没有使用过ruby,所以请原谅'less than rubysh/rspec'代码。但似乎确实管用。

    更新

    下面将通过不区分大小写的匹配找到基于部分标签的字段。这很适合我的需要。

    When= /^i enter "([^"]*)" in the "([^"]*)" field$/i do |value, fieldname|
      @thefield = all("label").detect { |l| (l.text =~ /#{fieldname}/i).nil? == false }
      if @thefield.nil? then
        raise Exception.new("Couldn't find field '#{fieldname}'")
      end
      fill_in @thefield[:for], :with=>value
    end