【问题标题】:Rspec content vs textRspec 内容与文本
【发布时间】:2012-10-13 09:21:54
【问题描述】:

我遇到过几个例子,人们用page.should have_selector "title", content: "my awsome content" 测试html 元素的内容,但这似乎总是通过。正确的调用似乎是page.should have_selector "title", text: "my awsome content"(注意text: 而不是content:)。

这个 Rspec 调用中的 content: 选择器是什么?

【问题讨论】:

  • 错了?尽管它可能取决于您使用的后端。 AFAIK Capybara 和 Webrat 使用 :text 并会忽略 :content,但我可能弄错了。

标签: ruby-on-rails rspec capybara


【解决方案1】:

简答:

have_selector 不支持:content 选项。

长答案:

Rspec 创建动态方法,将[].should be_empty 之类的调用转换为[].empty?.should == true,在您的情况下,将page.should have_selector "title", content: "my awesome content" 转换为page.has_selector?("title, content: "my awesome content").should == true

Capybara 提供了has_selector? 方法,它基本上只是将其参数传递给它的test/unit 样式断言assert_selector

def has_selector?(*args)
  assert_selector(*args)
rescue Capybara::ExpectationNotMet
  return false
end

assert_selector 然后再次将其参数传递给 Capybara finder 方法all(),如果找到任何匹配项则返回true,如果没有则引发异常(has_selector? 捕获然后返回@987654336 @ 与)。

def assert_selector(*args)
  synchronize do
    result = all(*args)
    result.matches_count? or raise Capybara::ExpectationNotMet, result.failure_message
  end
  return true
end

all 方法返回与查询匹配的所有结果。 This 是我们可以找到有关可接受选项的文档的地方:

# @overload all([kind], locator, options)
#   @param [:css, :xpath] kind                 The type of selector
#   @param [String] locator                    The selector
#   @option options [String, Regexp] text      Only find elements which contain this text or match this regexp
#   @option options [Boolean] visible          Only find elements that are visible on the page. Setting this to false
#                                              (the default, unless Capybara.ignore_hidden_elements = true), finds
#                                              invisible _and_ visible elements.
# @return [Array[Capybara::Element]]           The found elements

我们可以看到content 没有被列为有效选项,因此被忽略了。

【讨论】:

  • 需要注意的是 cmets 最终毫无意义;这是需要检查才能确定的代码。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-20
  • 1970-01-01
  • 1970-01-01
  • 2017-11-21
  • 2011-08-10
  • 2022-01-19
相关资源
最近更新 更多