I am trying to make a spec for my relationships controller and have a failure for the #create method (Couldn't find User with 'id'=). Can you please tell me how to fix this? Thanks for your help, if you have any question please ask. :)
relationships_controller:
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:
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!(:user) { create(:user) }
it "should require logged-in user to create relationship" do
post :create, followed_id: user.id
expect{
Relationship.create
}.to change(Relationship, :count).by(1)
redirect_to root_path
end
end
describe '#create' 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
Failure:
RelationshipsController
#create
should require logged-in user to destroy relationship
#create
should require logged-in user to create relationship (FAILED - 1)
Failures:
1) RelationshipsController#create should require logged-in user to create relationship
Failure/Error:
expect{
Relationship.create
}.to change(Relationship, :count).by(1)
expected #count to have changed by 1, but was changed by 0
relationship:
class Relationship < ActiveRecord::Base
#Associations
belongs_to :follower, class_name: "User"
belongs_to :followed, class_name: "User"
#Validations
validates :follower_id, presence: true
validates :followed_id, presence: true
end
user:
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
end
this worked out :
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