首页 > 解决方案 > RSpec/Capybara 找不到图像的链接

问题描述

我想使用 RSpec 和 Capybara 来模拟点击图像,但我做不到。

我的错误是这样的:

Failure/Error: click_on "icon_red_heart.png"

     Capybara::ElementNotFound:
       Unable to find visible css "#image-button"

规格/功能/posts_spec.rb

scenario "push an image" do  
  visit posts_path
  expect(page).to have_current_path(posts_path)
  find('#image-button').click
end

喜欢/_likes.html.erb

   <%= button_to post_like_path(post, like), id: "image-button",method: :delete, remote: true do %>

      <%= image_tag("icon_red_heart.png")%>

我不知道如何指定图像。

请教我。

标签: ruby-on-railsrubyrspeccapybara

解决方案


正如@jonrsharpe 指出的那样,您没有正确引用该按钮。引用元素的最有弹性的方法是给它一个 id 并通过该 id 引用它。

此外,由 by 创建的按钮button_to可能没有内容,在这种情况下,您需要告诉 Capybara 该按钮不可见。

将行更改为button_to

<%= button_to post_like_path(post, like), id: "image-button", remote: true do %>

然后将您的测试更改为如下所示:

scenario "push an image" do
  visit posts_path # Use the name of your path here
  find('#image-button', visible: false).click
end

顺便说一句,method: :delete在您的button_to链接中使用并没有达到您的预期。该方法自动设置为POST,这大概是您想要的。


推荐阅读