为什么我的 FactoryBots 没有创建 ID 或时间戳?

问题描述 投票:0回答:1

定义抽认卡机器人

FactoryBot.define do
    factory :flashcard do
        question { Faker::Quote.matz }
        time { Faker::Number.between(from: 1, to: 300) }
        association :box
    end
end

定义盒子机器人

FactoryBot.define do
    factory :box do 
        mod_p { Faker::Number.between(from: 1, to: 10) }
        box_number { Faker::Number.between(from: 1, to: 10) }
    end
end

在我的测试中制作盒子和抽认卡

box1 = FactoryBot.build(:box, box_number: 1)
box2 = FactoryBot.build(:box, box_number: 2)
box3 = FactoryBot.build(:box, box_number: 3)

subject(:flashcard) {FactoryBot.build(:flashcard, box: box2)}

出于某种原因,它们的创建没有 ID 或时间戳??有人有主意吗? enter image description here

在网上找到了一些关于 Rails 6 的链接,但我的项目并非如此。我正在使用 Rails 5.2

ruby-on-rails testing rspec factory-bot faker
1个回答
0
投票

根据您分享的代码,FactoryBot 不负责创建 ID 或时间戳。

ActiveRecord 框架通常负责在创建新记录时设置这些值。

您可以尝试使用

create
方法而不是
build
来创建记录,这应该会触发用于设置 ID 和时间戳的默认 ActiveRecord 行为:

box1 = FactoryBot.create(:box, box_number: 1)
box2 = FactoryBot.create(:box, box_number: 2)
box3 = FactoryBot.create(:box, box_number: 3)

subject(:flashcard) {FactoryBot.create(:flashcard, box: box2)}

这里是官方 ActiveRecord 文档的链接: https://api.rubyonrails.org/classes/ActiveRecord/Timestamp.html

希望对您有所帮助!

© www.soinside.com 2019 - 2024. All rights reserved.