2012-09-02 14 views
17

Wiem, że można łatwo przetestować należący do związku z wykorzystaniem shoulda:Shoulda belongs_to z CLASS_NAME i foreign_key

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

to możliwe, aby przetestować bardziej skomplikowanej relacji belongs_to korzystając shoulda? Coś takiego:

class Dog < ActiveRecord::Base 
    belongs_to :owner, :class_name => "Person", :foreign_key => "person_id" 
end 

Odpowiedz

2

Więc should-matchers README jest dość lekki na szczegółach, tylko o kilka przykładów. Zauważyłem, że jest dużo więcej informacji w RDoc klas, w przypadku belongs_to spojrzeć na association_matcher.rb. Pierwsza metoda polega na belongs_to z rdoc

# Ensure that the belongs_to relationship exists. 
    # 
    # Options: 
    # * <tt>:class_name</tt> - tests that the association makes use of the class_name option. 
    # * <tt>:validate</tt> - tests that the association makes use of the validate 
    # option. 
    # 
    # Example: 
    # it { should belong_to(:parent) } 
    # 
    def belong_to(name) 

Więc belongs_to tylko testy wsparcia dla :class_name i :validate.

3

Wiem, że trochę późno do partii, więc moje rozwiązanie może wymagać aktualnej wersji shoulda.

W chwili pisania tego artykułu jestem na v 2.4.0.

Nie potrzebowałem class_name lub with_foreign_key w mojej specyfikacji.

Upewnij się, że w swoim modelu określono class_name i foreign_key.

# model.rb: 
belongs_to :owner, inverse_of: :properties, class_name: "User", foreign_key: :owner_id 

# spec.rb: 
it { should belong_to(:owner) } 

Wynikiem:

should belong to owner 
Powiązane problemy