我正在接受这个测试
feature 'Edit post' do
let(:post) { build(:post) }
scenario 'can edit post' do
visit root_path
find(:xpath, "//a[@href='/posts/1']").click
click_link 'Edit'
fill_in 'Title', with: 'This is an updated post'
click_button 'Save'
expect(page).to have_content('Post was successfully updated')
expect(page).to have_content('This is an updated post')
end
end
当我运行测试时,我得到以下错误,据我所知,说Capybara无法找到链接
Failure/Error: find(:xpath, "//a[@href='/posts/1']").click
Capybara::ElementNotFound:
Unable to find xpath "//a[@href='/posts/1']"
但是,如果我在浏览器上打开应用程序,我可以点击show
(索引)中的root_path
链接并访问show动作,这让我觉得我的测试脚本出错了。我该如何解决这个问题?
UPDATE 我确实把page.html,这就是我得到的
<tbody>
<tr>
<td>Nihil neque corrupti atque qui eum omnis sapiente harum.</td>
<td>["Alias quas culpa expedita voluptatem vel. Eos aut autem tempora saepe odit iste. Iste ducimus dolorem a corrupti esse enim sint. Fugiat eum doloremque soluta ut voluptate sit. Nostrum unde in nobis quam ut adipisci quos cupiditate.", "Fugiat voluptatem qui totam fugit culpa et. Id omnis repellendus labore mollitia earum dignissimos ipsum. Eum rem qui excepturi culpa aut. Cum adipisci aspernatur nulla qui odio. Sequi minima doloremque iure ea possimus maiores alias."]</td>
<td><a href="/articles/1">Show</a></td>
<td><a href="/articles/1/edit">Edit</a></td>
<td><a data-confirm="Are you sure?" rel="nofollow" data-method="delete" href="/articles/1">Destroy</a></td>
</tr>
</tbody>
</table>
<br>
<a href="/articles/new">New Article</a>
</body>
答案 0 :(得分:0)
使用let
时,对象是懒惰的。这意味着它在您在测试中实际引用一次之前不存在。由于你从不引用它,它从未构建,因此不存在。如果在这种情况下切换到let!
,则会强制它构建
let!(:post) { create(:post) }
你遇到的另一个问题是你不能假设它会以id为1构建,所以你可能想在你的网址中使用post id
find(:xpath, ".//a[@href='/posts/#{post.id}']").click
(注意领先。没有这个,没有任何范围可行,在使用xpath表达式时会习惯将它放在那里 - https://github.com/teamcapybara/capybara#beware-the-xpath--trap)这实际上会更好地读取并且不那么脆弱
click_link(href: post_path(post))
尽管在功能测试中验证href不是最佳实践。你最好点击基于其中显示的文字的链接
click_link(post.name) #whatever is actually shown on the page