2012-10-24 5 views
5

私はRspecコントローラテストでアソシエーションをテストしようとしています。問題は、Factoryがattributes_forコマンドの関連付けを生成しないことです。だから、this postでの提案を以下の私の検証がそうのような私のコントローラの仕様に属性を定義した:FactoryGirl attributes_forとアソシエーション

EntitlementsController PUT update with valid params assigns the requested entitlement as @entitlement 
    Failure/Error: entitlement = Entitlement.create! valid_attributes 
    ActiveRecord::RecordInvalid: 
    Validation failed: User can't be blank, Country can't be blank, Client & expert are both FALSE. Please specify either a client or expert relationship, not both 

しかし:しかし

def valid_attributes 
    user = FactoryGirl.create(:user) 
    country = FactoryGirl.create(:country) 
    valid_attributes = FactoryGirl.build(:entitlement, user_id: user.id, country_id: country.id, client: true).attributes.symbolize_keys 
    puts valid_attributes 
end 

、コントローラのテストランは、私はまだ、次のエラーを取得するとき

{:id=>nil, :user_id=>2, :country_id=>1, :client=>true, :expert=>false, :created_at=>nil, :updated_at=>nil} 

答えて

4

あなたは0を持っているように見えます:ターミナルでvalid_attributes出力は明らかに、各valid_attributeがUSER_ID、COUNTRY_IDと専門家がtrueに設定されていることを示していvalid_attributesメソッドの最後の行にと入力します。これはnilを返します。あなたはEntitlement.create!にそれを渡すときに、ユーザーと国が空白であることについてエラーが出る理由は、など、だ

あなただけ持っているので、そのputs行を削除してください:

def valid_attributes 
    user = FactoryGirl.create(:user) 
    country = FactoryGirl.create(:country) 
    FactoryGirl.build(:entitlement, user_id: user.id, country_id: country.id, client: true).attributes.symbolize_keys 
end 

ところで、あなたが本当にいけませんのユーザーと国を作成してIDをbuildに渡すと、工場にusercountryの行を含めるだけで、工場でそのIDを渡すことができます。 FactoryGirl.build(:entitlement)を実行すると、自動的に作成されます(実際にはレコードは保存されません)。

+0

ああ、ありがとうございます。 –

関連する問題