2012-05-01 17 views
0

私はFactoryGirlを初めて使用しています。私は備品の世界から来ています。ファクトリーガールに関連付けを適切に設定するにはどうすればよいですか?

私は、次の2つのモデルがあります:

class LevelOneSubject < ActiveRecord::Base 
    has_many :level_two_subjects, :inverse_of => :level_one_subject 
    validates :name, :presence => true 
end 

class LevelTwoSubject < ActiveRecord::Base 
    belongs_to :level_one_subject, :inverse_of => :level_two_subjects 
    validates :name, :presence => true 
end 

をそして私は工場で、次のような何かをしたいと思います:

FactoryGirl.define do 
    factory :level_one_subject, class: LevelOneSubject do 
    factory :social_sciences do 
     name "Social Sciences" 
    end 
    end 

    factory :level_two_subject do 
    factory :anthropology, class: LevelTwoSubject do 
     name "Anthropology" 
     association :level_one_subject, factory: social_sciences 
    end 

    factory :archaelogy, class: LevelTwoSubject do 
     name "Archaelogy" 
     association :level_one_subject, factory: social_sciences 
    end 
    end 
end 

それから私はこのような仕様に工場を使用する場合:

01:

it 'some factory test' do 
    anthropology = create(:anthropology) 
end 

私はエラーを取得します

NoMethodError: undefined method `name' for :anthropology:Symbol 

誰でも助けてもらえますか?

level_one_subject_idが存在しなければならないとのみ、次のテストコードが動作することを私はその後、私はこのエラーを取得しない、工場での関連付けを設定していないが、私はエラーを取得する場合:

it 'some factory test' do 
    social_sciences = create(:social_sciences) 
    anthropology = create(:anthropology, :level_one_subject_id => social_sciences.id) 
end 

しかし、私なぜ協会と一緒に工場が働かないのか本当に知りたい。備品では、私はこれを何もしていませんでした。

+0

'NoMethodError'のスタックトレースを投稿できますか?私は、 'Symbol'に' name'を呼び出すメソッドが何であるか知るのに役立つと思います。必要に応じて、完全なトレースを取得するためにテストを実行するコマンドに '--trace'を追加してください。 –

答えて

0

私はあなたがFactoryGirlの仕組みではない「クラスファクトリ」によってファクトリをグループ化しようとしていると思います。これは、適切な名前が付けられていれば、工場名自体からActiveRecordクラスを推測します。ファクトリ名がクラス名と同じでない場合は、classという名前のクラスを使用してクラス名を明示的に指定する必要があります。これはうまくいくはずです:

FactoryGirl.define do 
    factory :level_one_subject do # automatically deduces the class-name to be LevelOneSubject 
     name "Social Sciences" 
    end 

    factory :anthropology, class: LevelTwoSubject do 
     name "Anthropology" 
     level_one_subject # associates object created by factory level_one_subject 
    end 

    factory :archaelogy, class: LevelTwoSubject do 
     name "Archaelogy" 
     level_one_subject # associates object created by factory level_one_subject 
    end 
end 
+0

正しい。 '' 'factory:level_one_subject'''を' '' 'social_sciences''と名付けたいなら、名前の隣に' 'class:LevelOneSubject'''を入れてレベル2の科目'' level_one_subject':factory =>:social_sciences'''(単に '' level_one_subject'''の代わりに) –

+0

うん、そうです。 – Salil

関連する問題