RSpec/Capybara 找不到 link 图像

RSpec/Capybara can't find link to image

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

我的错误是这样的:

Failure/Error: click_on "icon_red_heart.png"

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

spec/features/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/_likes.html.erb

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

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

我不知道如何指定图像。

请教教我

如@jonrsharpe 所示,您没有正确引用按钮。引用元素最灵活的方法是给它一个 id 并通过该 id 引用它。

此外,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

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