我試圖對MHartl's example進行規範測試。 如下圖所示,我的困難在於#關注用戶。Rspec(用於Michael Hartl示例)用於定義用戶之間的關係
class User < ActiveRecord::Base
# Associations
has_many :active_relationships, class_name: "Relationship",
foreign_key: "follower_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
對於我的規格:
require 'rails_helper'
RSpec.describe User, :type => :model do
let(:user) { build(:user) }
describe 'Validations' do
it 'has a valid factory' do
expect(user).to be_valid
end
it { should validate_presence_of(:email) }
it { should validate_presence_of(:password) }
it { should validate_confirmation_of(:password) }
end
let(:user) { create(:user) }
let(:other_user) { create(:user) }
describe '#following?' do
it "expect relationship between two users to be empty" do
expect(user.active_relationships).to be_empty
end
end
describe '#follow' do
it "creates the active relationship between two users" do
user.follow(other_user)
expect(user.active_relationships.first.followed_id).to eq(other_user.id)
end
it "creates the passive relationship between two users" do
user.follow(other_user)
expect(other_user.passive_relationships.first.follower_id).to eq(user.id)
end
end
describe '#unfollow' do
it "destroys the active relationship between two users" do
user.follow(other_user)
user.unfollow(other_user)
expect(user.active_relationships.find_by.followed_id).to change(Relationship, :count).by(-1)
end
end
我的錯誤:
1) User#unfollow destroys the active relationship between two users
Failure/Error: active_relationships.find_by(followed_id: other_user.id).destroy
NoMethodError:
undefined method `destroy' for nil:NilClass
2) User#follow creates the passive relationship between two users
Failure/Error: expect(other_user.passive_relationships.first.follower_id).to eq(user.id)
NoMethodError:
undefined method `passive_relationships' for #<User:0x0000010c4146e8>
如果您需要了解這個職位的詳細信息,請下跌免費問! 請告訴我,我可以瞭解更多關於這個規格測試。 感謝您的幫助:)
嗨,我剛剛更新了你的幫助!但我得到的錯誤:'你不能調用創建,除非父母被保存' – Jony
@Jony更新回答 –
該測試適用於'user.follow(other_user)',但沒有'user.following?(other_user)。應該be_valid' – Jony