我有一个用户模型,该模型本身具有多对多关系:用户A将用户B添加为朋友,并且用户B也自动成为用户A的朋友。
在rails控制台中执行以下步骤:
1)创建两个用户并保存:
2.3.1 :002 > u1 = User.new(name: "u1", email: "[email protected]")
=> #<User _id: 5788eae90640fd10cc85f291, created_at: nil, updated_at: nil, friend_ids: nil, name: "u1", email: "[email protected]">
2.3.1 :003 > u1.save
=> true
2.3.1 :004 > u2 = User.new(name: "u2", email: "[email protected]")
=> #<User _id: 5788eaf80640fd10cc85f292, created_at: nil, updated_at: nil, friend_ids: nil, name: "u2", email: "[email protected]">
2.3.1 :005 > u2.save
=> true
2)将用户u2添加为u1的朋友:
2.3.1 :006 > u1.add_friend u2
=> [#<User _id: 5788eaf80640fd10cc85f292, created_at: 2016-07-15 13:54:04 UTC, updated_at: 2016-07-15 13:55:19 UTC, friend_ids: [BSON::ObjectId('5788eae90640fd10cc85f291')], name: "u2", email: "[email protected]">]
3)检查他们的友谊:
2.3.1 :007 > u1.friend? u2
=> true
2.3.1 :008 > u2.friend? u1
=> true
我们可以看到,“相互友谊”是有效的。但是在我的测试中,这没有发生。这是我的测试:
require 'rails_helper'
RSpec.describe User, type: :model do
let(:user) { create(:user) }
let(:other_user) { create(:user) }
context "when add a friend" do
it "should put him in friend's list" do
user.add_friend(other_user)
expect(user.friend? other_user).to be_truthy
end
it "should create a friendship" do
expect(other_user.friend? user).to be_truthy
end
end
end
这是测试结果:
Failed examples:
rspec ./spec/models/user_spec.rb:33 # User when add a friend should create a friendship
我看到第二项测试失败的唯一原因是,我let
没有记住要在其他测试中使用的关联。我究竟做错了什么?
这是我的用户模型,以供参考:
class User
include Mongoid::Document
include Mongoid::Timestamps
has_many :posts
has_and_belongs_to_many :friends, class_name: "User",
inverse_of: :friends, dependent: :nullify
field :name, type: String
field :email, type: String
validates :name, presence: true
validates :email, presence: true
index({ email: 1 })
def friend?(user)
friends.include?(user)
end
def add_friend(user)
friends << user
end
def remove_friend(user)
friends.delete(user)
end
end
您需要将关系的创建移动到一个before
块中:
context "when add a friend" do
before do
user.add_friend(other_user)
end
it "should put him in friend's list" do
expect(user.friend? other_user).to be_truthy
end
it "should create a friendship" do
expect(other_user.friend? user).to be_truthy
end
end
在您的代码中,您仅在第一个it
块中运行它,而第二个块从头开始运行,并且不运行。
对于该before
块,它在每个it
块之前运行一次,因此规格应该通过。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句