Zakhar Slabodnik
Zakhar Slabodnik

Reputation: 13

RSpec: ActionView::Template::Error: undefined method `full_name' for nil:NilClass

I am getting this error, when starting spec tests. I understand that connection with the user is not set. What shall I do to pass the tests?

RSpec file : 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

My view: _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 failures:

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)>'

Upvotes: 1

Views: 3116

Answers (1)

Mark Rushakoff
Mark Rushakoff

Reputation: 258358

Without seeing your model for Post and User, it looks like you need to change

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

to

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

or

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

to correctly set up the association.

However, if your view is assuming that a Post always has a User, maybe your Post model should validate the presence of a User, or maybe you should change your view to handle the case where a Post does not have a User.

Upvotes: 2

Related Questions