如何在rails中断言选择一个类?

时间:2018-03-30 05:20:42

标签: ruby-on-rails ruby ruby-on-rails-4

我正在为我的项目使用rails 4.2,但我无法弄清楚如何检查特定类的缺席。我尝试使用assert_select 'p.class_name', falseassert_select '.class_name', false。它给出了同样的错误:

ArgumentError: ArgumentError: wrong number of arguments (given 3, expected 1) 

当我在做的时候

puts assert_select 'p', :attributes => {:class => 'class-name'}

它正在选择不应该完成的所有p标签。

当我通过这样的方式检查课堂内文本的存在时:

assert_select 'p.class_name', 'Hello_world'

它给出了同样的错误。

但后来我试着做了

assert_select 'p', 'Hello-world'

它工作正常。

最后,如何在rails 4.2中断言选择一个类?

1 个答案:

答案 0 :(得分:1)

对于HTML上的任意复杂断言,请使用我的assert_xpath。第一步是隔离<p>的容器。我们假设它位于<article>中,因此请使用//article的XPath。然后使用refute_xpath的XPath调用p[ contains(@class, "class-name") ]。把它们放在一起就像这样:

get :action

assert_xpath '//article' do
  refute_xpath 'p[ contains(@class, "class-name") ]'
  assert_xpath 'p[ "Hello World" = text() ]'
end

XPath表示法可以像关系数据库查询一样复杂和精细,与assert_select使用的CSS选择器不同。

将我的方法粘贴到您的test_helper.rb文件中:

class ActiveSupport::TestCase

  def assert_xml(xml)
    @xdoc = Nokogiri::XML(xml, nil, nil, Nokogiri::XML::ParseOptions::STRICT)
    refute_nil @xdoc
    return @xdoc
  end

  def assert_html(html=nil)
    html ||= response.body
    @xdoc = Nokogiri::HTML(html, nil, nil, Nokogiri::XML::ParseOptions::STRICT)
    refute_nil @xdoc
    return @xdoc
  end

  def assert_xpath(path, replacements={}, &block)
    @xdoc ||= nil  #  Avoid a dumb warning
    @xdoc or assert_html  #  Because assert_html snags response.body for us
    element = @xdoc.at_xpath(path, nil, replacements)

    unless element
      complaint = "Element expected in:\n`#{@xdoc}`\nat xpath:\n`#{path}`"
      replacements.any? and complaint += "\nwith: " + replacements.pretty_inspect
      raise Minitest::Assertion, complaint
    end

    if block
      begin
        waz_xdoc = @xdoc
        @xdoc = element
        block.call(element)
      ensure
        @xdoc = waz_xdoc
      end
    end

    return element
  end

  def refute_xpath(path, replacements={}, &block)
    @xdoc ||= nil  #  Avoid a dumb warning
    @xdoc or assert_html  #  Because assert_html snags @response.body for us
    element = @xdoc.at_xpath(path, nil, replacements)

    if element
      complaint = "Element not expected in:\n`#{@xdoc}`\nat xpath:\n`#{path}`"
      replacements.any? and complaint += "\nwith: " + replacements.pretty_inspect
      raise Minitest::Assertion, complaint
    end
  end

end