2017-08-24 54 views
0

我有這兩款車型FactoryGirl :: InvalidFactoryError:驗證失敗:<Class>必須存在(的ActiveRecord :: RecordInvalid)

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

我終於找到了解決方案。關鍵的失蹤是在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

我已經試過了,但我發現了另一個錯誤:'*後 - Mysql2 ::錯誤:無法添加或更新子行:外鍵約束fails' – Lykos

+0

@Lykos如果子表中包含一些數據,而這些數據不在父表中,則會出現這種情況。在你的情況下,'post.user_id'是'user.id'的外鍵,而post表包含'user_id',它不存在於用戶表中。 – Roshan

+0

不知道我是否理解你在說什麼,但是爲了關聯帖子 - 用戶'add_reference:posts,:user,foreign_key:true,在::id'之後生成了此遷移。這就是我設置'post'的方式。 user_id' – Lykos

相關問題