我在RSpec中有一个测试,如果列表中的某篇文章属于登录用户,则检查编辑链接:
let(:user) { Fabricate(:user) }
before do
visit new_user_session_path
fill_in 'Email', :with => user.email
fill_in 'Password', :with => user.password
click_button 'Sign in'
end
describe 'when user has a self-authored article' do
let(:article) { Fabricate(:article, :author_id => user.id) }
before { visit articles_path }
it { should have_link('Edit article', :href => edit_article_path(article)) }
end
这些是它测试的视图:
# articles/new.html.erb
<% provide(:title, 'Articles') %>
<h1>Articles</h1>
<% if user_signed_in? %>
<%= link_to 'Post article', new_article_path %>
<% end %>
<%= render @articles %>
<%= will_paginate %>
这是它测试的具体视图:
# articles/_article.html.erb
<% if user_signed_in? %>
<% if current_user.id == article.author.id %>
<%= link_to 'Edit article', edit_article_path(article) %>
<% end %>
<% end %>
当我运行测试时,我收到以下错误:
失败/错误:它{should have_link('编辑文章',:href =&gt; edit_article_path(article))}
expected link "Edit article" to return something
我检查了我的浏览器以确认测试是正确的,但链接似乎按预期显示。我哪里做错了?如何让测试通过?
答案 0 :(得分:2)
我猜测let(:article) { Fabricate(:user, :author_id => user.id) }
正在创建用户,而不是文章。
答案 1 :(得分:0)
我已经弄清楚了。事实证明,我对let
的工作原理有误解。我以为它可以在before
之前执行,但我错了。我通过在before
块
describe 'when user has a self-authored article' do
before do
@article = Fabricate(:article, :author_id => user.id)
visit articles_path
end
it { should have_link('Edit article', :href => edit_article_path(@article)) }
end
end