我正在尝试为AJAX调用编写测试。该功能适用于制作,但我遇到了Capybara的问题。似乎find(".selector").click
在同一场景中不能被调用两次。
场景#1通过,但场景#2在第二个find(".article__expand").click
上出现此错误:
Failure/Error: find(".article__expand").click
Capybara::ElementNotFound:
Unable to find css ".article__expand"
我正在使用CSS选择器,因为链接的正文是一个glyphicon span。有办法解决这个问题吗?
require "rails_helper"
RSpec.feature "Users can toggle article descriptions" do
let(:article) { FactoryGirl.create(:article, description: "Article description") }
context "all users" do
before do
visit article_path(article)
end
scenario "description is hidden until clicked" do
expect(page).to_not have_content("Article description")
find(".article__expand").click
expect(page).to have_content("Article description")
end
scenario "description can be toggled" do
expect(page).to_not have_content("Article description")
find(".article__expand").click
expect(page).to have_content("Article description")
find(".article__expand").click
expect(page).to_not have_content("Article description")
end
end
end
这是如何进行通话的。我在description
上使用自定义resources :articles
获取成员。
# views/articles/_article.html.erb
<div class="article" id="article-<%= article.id %>">
<%= link_to description_article_path(article), remote: true, class: "article__expand" do %>
<span class="glyphicon glyphicon-plus"></span>
<% end %>
<div class="article__info">
</div>
</div>
# views/articles/description.js.erb
$(function() {
if ($("#article-<%= @article.id %> .article__description").length) {
$("#article-<%= @article.id %> .article__description").toggle();
} else {
$.getJSON( '/articles/<%= @article.id %>.json', function( data ) {
var description = ('<p class="article__description">' + data.description + '</p>')
$('#article-<%= @article.id %> .article__info').prepend(description);
});
}
});
答案 0 :(得分:0)
为了调试这些事情,我建议采取以下步骤:
gem install launchy
Launch说:Launchy就是为了在ruby程序中启动外部应用程序的常用方法。
在期望失败之前,在规范中使用save_and_open_page
。有点像下面这样:
scenario "description can be toggled" do
expect(page).to_not have_content("Article description")
find(".article__expand").click
save_and_open_page
expect(page).to have_content("Article description")
find(".article__expand").click
....
这将使调试更容易。还要考虑采用不同的方法并使用Capybara方法,例如:
=Clicking links and buttons=
click_link('id-of-link')
click_link('Link Text')
click_button('Save')
click('Link Text') # Click either a link or a button
click('Button Value')
这些来自这里发现的超级有用的Capybara备忘单 - https://gist.github.com/zhengjia/428105