0

对于第 12 章的练习 1,我无法弄清楚为什么当我从 User 模型中取出 :dependent => :destroy 时我的测试没有失败

我的测试

@user.follow!(@followed)
@followed.destroy
@user.followers.should_not include(@followed)

我的模型,没有 :dependent => :destroy

has_many :relationships, 
  :foreign_key => "follower_id"
has_many :following, :through => :relationships, :source => :followed
has_many :reverse_relationships,
  :foreign_key => "followed_id"
  :class_name => "Relationship"
has_many :followers, :through => :reverse_relationships, :source => :follower

仍然导致所有测试通过

4

1 回答 1

0

您的测试逻辑似乎有错误....

  #1  @followed.destroy
  #2  @user.followers.should_not include(@followed)

代码的第 1 行,我认为当您对其调用 destroy 时,@followed 变为 nil,而在第 2 行中,@user.followers 中没有“nil”对象,因此这可能就是您的测试不断通过的原因。我使用了以下代码,它按预期工作:

  r1 = @user.follow!(@followed)
  r2 = @followed.follow!(@user)
  @user.destroy
  [r1, r2].each do |relationship|
    Relationship.find_by_followed_id(relationship.followed_id).should be_nil
  end
于 2012-01-27T03:56:17.100 回答