0

假设我有两个模型

class User < ActiveRecord::Base
  has_many :friendships, :dependent => :destroy
  has_many :followings, :through => :friendships, :foreign_key => "followed_id"
end

class Friendship < ActiveRecord::Base
  belongs_to :user 
  belongs_to :following, :class_name => "User", :foreign_key => "followed_id"
end

现在在我的 user_spec.rb 我有这个测试

it "should delete all friendships after user gets destroyed" do
  @user.destroy
  [@friendship].each do |friendship|
    lambda do
      Friendship.find(friendship)
    end.should raise_error(ActiveRecord::RecordNotFound)
  end
end

这是测试 :dependent => :destroy 关系的正确位置吗?或者这是否属于friendship_spec.rb 或者我测试这两个规范中的哪一个无关紧要?

4

2 回答 2

1

这种事情有时是一个品味问题,但我认为规范User可能是测试这一点的最佳场所。您为开始测试而调用的方法是 on 方法User,因此与其他测试一起测试它也是有意义的User

于 2012-12-12T19:07:32.470 回答
1

您可以考虑使用shoulda_matchers来测试您的关联:

# user_spec.rb
it { should have_many(:friendships).dependent(:destroy) }

# friendship_spec.rb
it { should belong_to(:user) }

让每个模型测试自己的关联是最好的方法恕我直言。

于 2012-12-12T21:11:12.290 回答