我有一个用户模型和一个友谊模型。

class Friendship < ActiveRecord::Base
  belongs_to :sender, :class_name=>'User', :foreign_key=>'sender_id'
  belongs_to :receiver, :class_name=>'User', :foreign_key=>'receiver_id'

  validates_presence_of :receiver_id, :sender_id
  validates_associated :receiver, :sender
end

class User < ActiveRecord::Base
  has_many :sent_friendships, :class_name => "Friendship", :foreign_key => "sender_id", :dependent => :destroy
  has_many :received_friendships, :class_name => "Friendship", :foreign_key => "receiver_id", :dependent => :destroy
end

我的rspec测试之一是
describe Friendship do

  before(:each) do
    @valid_attributes = {
      :sender_id => 1,
      :receiver_id => 2,
      :accepted_at => nil
    }
  end

  it "should not be valid with non-existant receiver_id" do
    f = Friendship.new(@valid_attributes)
    f.receiver_id = 99999
    f.should_not be_valid
  end
end

测试不应该有效,因为没有User_id 9999的用户。但是测试说的友谊模型有效。

为什么要死?

编辑:

但是我想像提到的那样测试->而不直接分配发件人。那不可能吗?

最佳答案

如果您希望模型以这种方式工作,请更改此设置:

validates_presence_of :receiver_id, :sender_id

对此:
validates_presence_of :receiver, :sender

09-18 17:17