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 tests 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 does not have to be valid because there is no user with user_id 9999. But the test says that the friendship model is valid.

Why the hell?

EDIT:

But I want to test, as mentioned, β†’ without directly assigning the sender. Is it impossible?

+6
ruby ruby-on-rails
source share
4 answers

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

 validates_presence_of :receiver_id, :sender_id 

:

 validates_presence_of :receiver, :sender 
+11
source share

The Rails documentation for validates_associtated states the following:

NOTE. This check will not work if an association has not been assigned. If you want to make sure the association is present and guaranteed to be valid, you also need to use validates_presence_of.

You have not assigned an association. Modify your test as follows and it should pass:

 it "should not be valid with non-existant receiver_id" do f = Friendship.new(@valid_attributes) f.receiver_id = 99999 f.receiver = nil # Note this line f.should_not be_valid end 
+2
source share

There also floats a plugin that does this ... validates_existence_of .

http://blog.hasmanythrough.com/2007/7/14/validate-your-existence

+2
source share

Hmm ..

after I found only this blog entry and won-fix-ticket in the rails beacon:

Blog post with solution

Lighthouse-wont-fix-ticket

i switched to my solution:

 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 validate :sender_exists validate :receiver_exists protected def sender_exists errors.add("sender_id", "not existant") unless User.exists?(self.sender_id) end end 
+1
source share

All Articles