'let' 不记忆 rspec 中的值

'let' doesn't memoize values in rsepc

我有一个用户模型,它本身有一个多对多的关系:用户 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 

如我们所见,"mutual friendship" 有效。但在我的测试中并没有发生。这是我的测试:

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 块之前是 运行 一次,因此规范应该通过。