FactoryGirl :: InvalidFactoryError:验证失败:<class>必须存在(ActiveRecord :: RecordInvalid)

时间:2017-08-24 21:15:57

标签: 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

2 个答案:

答案 0 :(得分:1)

我最终找到了解决方案。缺少的关键是let strNSRange = dogString.range(nsRange: NSRange(range, in: dogString)) print((dogString as NSString).substring(with: strNSRange!)) // extension String { func range(nsRange: NSRange) -> NSRange? { guard let from16 = utf16.index(utf16.startIndex, offsetBy: nsRange.location, limitedBy: utf16.endIndex), let to16 = utf16.index(utf16.startIndex, offsetBy: nsRange.length, limitedBy: utf16.endIndex), let from = from16.samePosition(in: self), let to = to16.samePosition(in: self) else { return nil } return NSMakeRange(from.encodedOffset, to.encodedOffset) } }

association :user

答案 1 :(得分:-1)

尝试以下方法:

belongs_to :user, optional: true
  

4.1.2.11:可选

     

如果将:optional选项设置为true,则表示存在   相关对象无法验证。默认情况下,此选项已设置   为假。

您可以参考docs了解更多信息。