1

如果列表中的一篇文章属于登录用户,我在 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('Edit article', :href => edit_article_path(article)) }

   expected link "Edit article" to return something

我检查了我的浏览器以确认测试是正确的,但链接似乎按预期显示。我哪里做错了?如何使测试通过?

4

2 回答 2

2

我猜这let(:article) { Fabricate(:user, :author_id => user.id) }是在创建用户,而不是文章。

于 2012-04-06T06:25:33.560 回答
0

I have figured it out. It turns out that I had a misunderstanding of how let works. I thought it could be executed before before, but I was wrong. I fixed the issue by fabricating the object inside the before block

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
于 2012-04-06T08:19:25.087 回答