2017-08-24 5 views
0

(ActiveRecordは:: RecordInvalid)が存在している必要がありFactoryGirl :: InvalidFactoryError:検証に失敗しました:<Class>は、私はこれらの二つのモデルを持っている

class User < ApplicationRecord 
    devise :database_authenticatable, :registerable, 
     :recoverable, :rememberable, :trackable, :validatable 

    has_many :posts 
end 

class Post < ApplicationRecord 
    belongs_to :user 
end 

これらは私の工場です

FactoryGirl.define do 
    factory :user do 
    id 1 
    first_name 'John' 
    last_name 'Doe' 
    sequence(:email) { |n| "tester#{n}@example.com" } 
    password 'secretpassword' 
    end 
end 

FactoryGirl.define do 
    factory :post do 
    user_id 1 
    title 'This is a title' 
    body 'This is a body' 
    published_at Time.now 
    end 
end 

私は次のテスト私は実行すると、次のエラーが表示されます:

RSpec.describe User, type: :model do 
    let(:user) { build(:user) } 
    it { expect(user).to have_many(:posts) } 
end 

RSpec.describe Post, type: :model do 
    let(:post) { build(:post) } 
    it { expect(post).to belong_to(:user) } 
end 

# Error I get: 
FactoryGirl::InvalidFactoryError: 
    The following factories are invalid: 

    * post - Validation failed: User must exist (ActiveRecord::RecordInvalid) 

どうすればこの問題を解決できますか?

これも私のDBスキーマである

create_table "posts", force: :cascade, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8" do |t| 
    t.integer "user_id" 
    t.string "title" 
    t.text  "body",   limit: 65535 
    t.datetime "published_at" 
    t.datetime "created_at",     null: false 
    t.datetime "updated_at",     null: false 
    t.index ["user_id"], name: "index_posts_on_user_id", using: :btree 
    end 

create_table "users", force: :cascade, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8" do |t| 
    # Whatever devise generates 
end 

答えて

0

最終的に解決策が見つかりました。外部キー制約fails`:子行を追加または更新することはできません: - Mysql2 ::エラー `*ポスト:キーは、私はすでにこれを試してみましたが、私は別のエラーを取得していますassociation :user

FactoryGirl.define do 
    factory :post do 
    title 'This is a title' 
    body 'This is a body' 
    published_at Time.now 
    association :user 
    end 
end 
0

次のことを試してみてください。

belongs_to :user, optional: true 

4.1.2.11 :optional

If you set the :optional option to true, then the presence of the associated object won't be validated. By default, this option is set to false.

あなたはより多くの情報のためdocsを参照してもよいです。

+0

た行方不明になりました – Lykos

+0

@Lykosこれは、子テーブルに、親テーブルにない外部キーを持つデータが含まれている場合に発生します。あなたのケースでは、 'post.user_id'は' user.id'の外部キーであり、ポストテーブルは 'user_id'を含んでいます。これはユーザテーブルにはありません。 – Roshan

+0

あなたが何を言っているのか分かりませんが、この移行を生成して、ユーザーを 'add_reference:posts、:user、foreign_key:true、after::id'というように関連づけました。 user_id' – Lykos

関連する問題