我有一个用户模型,其本身具有多对多关系:用户A将用户B添加为朋友,并且用户B自动成为用户A的朋友。
在rails控制台中执行以下步骤:
1)创建两个用户并保存:
2.3.1 :002 > u1 = User.new(name: "u1", email: "u1@mail.com")
=> #<User _id: 5788eae90640fd10cc85f291, created_at: nil, updated_at: nil, friend_ids: nil, name: "u1", email: "u1@mail.com">
2.3.1 :003 > u1.save
=> true
2.3.1 :004 > u2 = User.new(name: "u2", email: "u2@mail.com")
=> #<User _id: 5788eaf80640fd10cc85f292, created_at: nil, updated_at: nil, friend_ids: nil, name: "u2", email: "u2@mail.com">
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: "u2@mail.com">]
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
答案 0 :(得分:3)
您需要将关系的创建移动到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
块之前运行一次,因此规范应该通过。