2017-08-24 56 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

相关问题