dimanche 8 mai 2016

RSpec failure ( undefined method `id' for nil:NilClass ) with has_many through model

I can't make the spec to pass in the relationships controller. I have to change something about my object in the controller or the controller_spec. Feel free to ask any doubt about my controller... thanks

user.rb

class User < ActiveRecord::Base

  # Associations
  has_many :active_relationships, class_name:  "Relationship",
                                  foreign_key: "follower_id",
                                  dependent:   :destroy
  has_many :passive_relationships, class_name:  "Relationship",
                                  foreign_key: "followed_id",
                                  dependent:   :destroy
  has_many :following, through: :active_relationships, source: :followed
  has_many :followers, through: :passive_relationships, source: :follower

  # Follows a user.
  def follow(other_user)
    active_relationships.create(followed_id: other_user.id)
  end

  # Unfollows a user.
  def unfollow(other_user)
    active_relationships.find_by(followed_id: other_user.id).destroy
  end

  # Returns true if the current user is following the other user.
  def following?(other_user)
    following.include?(other_user)
  end
end

relationships_controller.rb

class RelationshipsController < InheritedResources::Base

  def create
    user = User.find(params[:followed_id])
    current_user.follow(user)
    redirect_to user
  end

  def destroy
    user = Relationship.find(params[:id]).followed
    current_user.unfollow(user)
    redirect_to user
  end
end

relationships_controller_spec.rb

require 'rails_helper'

describe RelationshipsController do
  let(:relationship) { create(:relationship) }
  let(:user) { create(:user) }

  before do
    sign_in :user, create(:user)
  end

  describe '#create' do
    let!(:followed) { create(:user) }
    it "should require logged-in user to create relationship" do
      expect{
        post :create, followed_id: followed.id
      }.to change(Relationship, :count).by(1)
      redirect_to root_path
    end
  end

  describe '#destroy' do
    let!(:relationship) { create(:relationship) }

    it "should require logged-in user to destroy relationship" do
      expect {
        delete :destroy, id: relationship.id
      }.to change(Relationship, :count).by(-1)
      redirect_to root_path
    end
  end
end

Failures:

  1) RelationshipsController#destroy should require logged-in user to destroy relationship
     Failure/Error: active_relationships.find_by(followed_id: other_user.id).destroy

     NoMethodError:
       undefined method `id' for nil:NilClass

Aucun commentaire:

Enregistrer un commentaire