Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

validates_associated and validates_presence_of not working as expected with rspec?

I have a User model and a Friendship-Model.

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

and one of my rspec-test is

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

The test shouldnt be valid, because there is no User with user_id 9999. But the test say's the friendship-model is valid.

Why the hell?

EDIT:

But I want to test like mentioned -> without assigning the sender directly. Isn't that possible??

like image 729
BvuRVKyUVlViVIc7 Avatar asked Apr 15 '09 17:04

BvuRVKyUVlViVIc7


1 Answers

If you want your model to work that way, change this:

validates_presence_of :receiver_id, :sender_id

to this:

validates_presence_of :receiver, :sender
like image 50
Elliot Nelson Avatar answered Nov 10 '22 00:11

Elliot Nelson