【问题标题】:How to assert that a (delete) path - image combination is absent如何断言(删除)路径 - 图像组合不存在
【发布时间】:2015-04-14 13:16:54
【问题描述】:

在我看来,我有:

<%= link_to image_tag("remove.png", title: "remove"), user, method: :delete, data: { confirm: "This will permanently remove the user" } %>

我正在尝试编写一个测试以证明不存在此类链接和图像。我尝试了几个版本,但似乎都没有。我的最佳猜测是:

assert_select 'a[href=?]', user_path(user), method: :delete, count: 0
assert_select 'image_path(remove.png)', count: 0

第一个 assert_select 的测试运行,但计数 1 个这样的链接,而我很确定这样的链接不存在。我认为它正在计算确实存在 user_path(user) 的 show 方法(而不是 delete 方法)。

第二个 assert_select 的测试产生错误:

unexpected '.' after '["remove"]' (called from block (2 levels) in <class:SiteLayoutTest> at /test/integration/site_layout_test.rb:46)
DEPRECATION WARNING: The assertion was not run because of an invalid css selector.

【问题讨论】:

  • 图片和链接不存在是什么情况?
  • 它们只有在管理员登录时才可见(在索引视图中)。否则它们不可见。在服务器上手动测试似乎可以确认代码正常工作。所以似乎是测试写错了,特别是两个 assert_select 行(测试的其余部分工作正常)。

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


【解决方案1】:
assert_select "a[href=#{user_path(user)}][data-method=delete]", false, "This page must contain no delete user links"

更新

图片也一样:

assert_select "img[src=#{image_path('remove.png')}]", false, "This page must contain no remove image"

在 css 选择器(第一个参数)中,您可以使用任何 [attr=value] 对 html 标记元素 (&lt;... attr="value"/&gt;),甚至可以将它们组合在一起 [attr1=value1][attr2=value2][...]

更新 1

image_path 辅助方法在测试类中不可用。一种解决方法是(只要您的路径中没有另一个带有“删除”的图像):

assert_select "img[src*=remove]", false, "This page must contain no remove image"

但更好的解决方案是完全不依赖路径并使用class 属性。 内景:

<%= image_tag 'remove.png', class: 'image-remove') %>

在测试方法中:

assert_select "img.image-remove", false, "This page must contain no remove image"

【讨论】:

  • 谢谢,这适用于测试链接不存在。是否还有一种方法可以单独测试图像是否不存在?
  • 有意义吗?图片在链接标签内,隐藏链接时不显示。
  • 我同意这种情况。但是对于另一个测试,我想测试以管理员身份登录时,链接和图像都存在。我现在知道如何为链接而不是图像执行此操作。我想分别测试链接和图片,因为可能是图片在服务器上不可用,导致链接没有图片。
  • 虽然它对链接有效,但对图像无效。似乎 image_path 方法在测试中不可用。我收到错误消息:NoMethodError: undefined method 'image_path' for .
  • 有可能。您可以在结果标记中使用 img 标记的 src 属性值,而不是 #{image_path(...)}。或者看到这个:stackoverflow.com/questions/29437053/using-helpers-in-minitest/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-04-05
  • 2014-03-27
  • 1970-01-01
  • 1970-01-01
  • 2013-06-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多