RSpec:ActionView :: Template :: Error:nil的未定义方法`full_name':NilClass

时间:2012-05-04 14:08:21

标签: ruby ruby-on-rails-3 rspec

启动规范测试时出现此错误。我知道没有设置与用户的连接。我该怎么办才能通过考试?

RSpec文件:posts_controller_spec.rb

require 'spec_helper'
include Devise::TestHelpers

describe PostsController do
  render_views

  context "Logged in as user" do
    let(:user) { FactoryGirl.create(:user) }

    before { login_as(user) }

    context "on viewing index page" do
      let!(:p) { FactoryGirl.create(:post) }

      before { get :index }

      it { should respond_with(:success) }

      it { assigns(:posts).should == [p] }
    end
  end
end

我的观点:_home.html.erb

<% @posts.each do |post| %>
  <%= link_to post.title, post %>

    <%= post.user.full_name %></i></b><hr />

    <div>
      <%= post.content.html_safe %>
    </div>
<% end %>

RSpec失败:

PostsController Logged in as user on viewing index page 
     Failure/Error: before { get :index }
     ActionView::Template::Error:
       undefined method `full_name' for nil:NilClass
     # ./app/views/posts/_home.html.erb:5:in `block in _app_views_posts__home_html_erb__709569216_93469850'
     # ./app/views/posts/_home.html.erb:2:in `each'
     # ./app/views/posts/_home.html.erb:2:in `_app_views_posts__home_html_erb__709569216_93469850'
     # ./app/views/posts/index.html.erb:1:in `_app_views_posts_index_html_erb___825727830_90641210'
     # ./spec/controllers/posts_controller_spec.rb:33:in `block (4 levels) in <top (required)>'

1 个答案:

答案 0 :(得分:2)

没有看到PostUser的模型,看起来您需要更改

let!(:p) { FactoryGirl.create(:post) }

let!(:p) { FactoryGirl.create(:post, :user => user) }

let!(:p) { FactoryGirl.create(:post, :user_id => user.id) }

正确设置关联。

但是,如果您的观点假定Post 总是User,那么您的Post模型可能会验证是否存在{{1}或者,或者您应该更改视图以处理User没有Post的情况。