# RSpec, validates\_presence\_of, and foreign\_key

**URL:** <https://www.ruby-forum.com/t/rspec-validates-presence-of-and-foreign-key/131435>\
**Category:** Rails\
**Created:** [March 10, 2008, 2:30am UTC](https://www.ruby-forum.com/t/rspec-validates-presence-of-and-foreign-key/131435 "2008-03-10T02:30:37Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![Pietro](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/p/47e85d/32.png) [@Pietro](https://www.ruby-forum.com/u/Pietro)\
**Post date:** [March 10, 2008, 2:30am UTC](https://www.ruby-forum.com/t/rspec-validates-presence-of-and-foreign-key/131435/1 "2008-03-10T02:30:37Z")

</div>

I’m having trouble with validation and RSpec/spec::rails.

I have an Item model which acts\_as\_ratable. Item has\_many :ratings  
(Rating is another model which essentially maps users to ratings). In  
the Rating model I have

belongs\_to :item, :foreign\_key =\> ‘rateable\_id’  
validates\_presence\_of :rateable\_id

In the Rails documentation it says to validate on :rateable\_id rather  
than :rateable, so this is what I’ve done above.

Now, in my specs I have problems. If I do something like

@rating = Rating.new(…) # an invalid Rating  
@rating.valid?  
@rating.errors.on(:rateable\_id).should\_not be\_nil

(to ensure that an invalid Rating cant be saved), it fails (the  
validation is ineffectual).

If I change back to

validates\_presence\_of :rateable

and check for errors.on.(:ratable), that spec will work. However that  
causes another problem. In that case, if I do this

@rating = Rating.new(…) # a valid Rating  
@rating.save!

(which I am doing to test some after\_save hooks) it fails and says  
Rateable cannot be blank.

I’m quite confused. I think its related to the foreign\_key because I’m  
not having trouble with any of the other validations. Can anyone shed  
some light on the situation?

Thanks.
