0
다자간 관계가있는 사용자 모델이 있습니다. 사용자 A는 사용자 B를 친구로 추가하고 자동으로 사용자 B는 사용자 A의 친구가됩니다. 너무.'let'은 rsepc의 값을 메모하지 않습니다.
레일 콘솔에서 다음 단계를 수행 :
이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) U1의 친구로 사용자 U2를 추가
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
는 시험이다가 발생할 : 내
let
가에서 사용할 수있는 연결을 memoizing되지 않기 때문에 내가 두 번째 테스트에 볼 수있는 유일한 이유는 실패
Failed examples:
rspec ./spec/models/user_spec.rb:33 # User when add a friend should create a friendship
입니다 다른 테스트. 내가 도대체 뭘 잘못하고있는 겁니까? 당신은 before
블록으로 관계의 생성을 이동해야
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
'메모'하시겠습니까? – Sid
오른쪽, @ 시드. 질문이 업데이트되었습니다. – rwehresmann
테스트를 위해 데이터베이스를 정리하는 데 사용하는 전략은 무엇입니까? 'user {add_friend (other_user)} '를'before {}'에 추가해야 할 수도 있으므로 각 예제 앞에 나타납니다. 가장 일반적인 전략은 모든 예가 나온 후에 DB를 정리합니다. – Leito