ruby-on-rails - FactoryGirl::InvalidFactoryError:验证失败:<Class> 必须存在 (ActiveRecord::RecordInvalid)

标签 ruby-on-rails rspec tdd shoulda

我有这两个模型

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)

我该如何解决这个问题?

这也是我的数据库架构

  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

最佳答案

我最终找到了解决方案。缺少的关键是关联: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

关于ruby-on-rails - FactoryGirl::InvalidFactoryError:验证失败:<Class> 必须存在 (ActiveRecord::RecordInvalid),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45871009/

相关文章:

ruby-on-rails - 在 Rails 4 中使用 Devise 允许用户使用嵌套属性

ruby-on-rails - 测试 Stripe 适用于 js : true,,但它会使其他组件无法正常工作

ruby-on-rails - 未定义的方法 `on_ride_photo='

ruby-on-rails - 对于 database.yml 中的池大小,我应该考虑什么?

javascript - 以增量方式显示 SQLite 数据库中的数据

php - Symfony2 Doctrine MongoDB 回滚

java - 用于测试分布式系统的集成测试框架?

ruby-on-rails - 未定义的方法 `tempfile' 为 "\x89PNG\r\n":String

ruby-on-rails - Rspec 不会让这个微不足道的代码失败,即使它应该

tdd - Rust 的持续测试驱动开发