Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shoulda belongs_to with class_name and foreign_key

Tags:

I know you can easily test a belongs to relationship using Shoulda:

describe Dog dog   it { should belong_to(:owner) } end 

Is it possible to test a more complicated belongs_to relationship using Shoulda? Something like this:

class Dog < ActiveRecord::Base   belongs_to :owner, :class_name => "Person", :foreign_key => "person_id" end 
like image 932
LandonSchropp Avatar asked Sep 02 '12 08:09

LandonSchropp


1 Answers

You should be able to use:

it { should belong_to(:owner).class_name('Person') } 

Shoulda's belong_to matcher always reads the foreign_key from the association and tests that it is a valid field name, so you don't need to do anything more.

(See Shoulda::Matchers::ActiveRecord::AssociationMatcher#foreign_key_exists? and associated methods)

like image 54
georgebrock Avatar answered Oct 04 '22 21:10

georgebrock