0

Rails 3.0、rspec 2.0、および factory_girl を実行しています。私が取り組んでいる単純化されたシナリオは次のとおりです。ユーザーは一度に 1 つのプランにのみサブスクライブできます。

# user.rb
class User < ActiveRecord::Base
  has_one :plan
  attr_accessible :login, :plan_id

end

# plan.rb
class Profile < ActiveRecord::Base
 attr_accessible :plan
end

# user_factory.rb
Factory.define :user do |u|
  u.login "test"
  u.association :plan
end

#plan_factory.rb
Factory.define :plan do |p|
   p.name "plan1"
end

rspec spec/models/user_spec.rb を実行すると、次のエラーが発生しました。

失敗/エラー: user = Factory(:user) SQLite3::ConstraintException: users.plan_id を NULL にすることはできません

#spec/models/user_spec.rb
require File.dirname(__FILE__) + '/../spec_helper'

describe User do
  it "should be valid" do
    user = Factory(:user)
    #User.new.should be_valid
    user.should be_valid
  end
end

私が間違っていることは何ですか?私はこの非常に単純なシナリオで立ち往生しており、非常にイライラしています。その時点で、BDD は地獄のように私を遅くします!

4

2 に答える 2

0

has_one関連付けを正しく実装していないようです。リレーションシップの外部キーは、ディレクティブhas_one -- belongs_toを持つモデルに対応するテーブルに入れる必要があります。belongs_to確認してください -- 表で定義されているdb/schema.rbことがわかると思います。モデルに を含めたい場合は、 から削除して に追加する必要があります。plan_idusersUserPlanplan_idusersuser_idplans

Plana has oneにしたい場合はUser、スキーマをそのままにして、 has_one :userinPlanbelongs_to :planin に入れますUser

于 2010-10-14T05:30:56.170 に答える
0

ユーザーは 1 つのプランに加入します。したがって、ユーザーには 1 つのプランがあり、プランは多くのユーザーに関連付けられます。だから私はそれを正しく理解したと思います。エラーはユーザー ファクトリにありました。交換する

u.association :plan

u.association :plan, :factory => :plan

問題を修正しました。

問題が解決しました!

于 2010-11-02T00:46:25.167 に答える