我一直在研究介绍工厂机器人的教程,以帮助进行测试。本教程在其他方面还是不错的,但我无法解决解决此错误的方法:
Failure/Error: let!(:items) { create_list(:item, 20, todo_id: todo.id) }
KeyError:
Trait not registered: "todo_id"
items_spec.rb
RSpec.describe 'Items API' do
# Initialize the test data
let!(:todo) { create(:todo) }
let!(:items) { create_list(:item, 20, todo_id: todo.id) }
let(:todo_id) { todo.id }
let(:id) { items.first.id }
...
FB items.rb
FactoryBot.define do
factory :item do
name { Faker::StarWars.character }
done { false }
todo_id nil
end
end
FB todos.rb
FactoryBot.define do
factory :todo do
title { Faker::Lorem.word }
created_by { Faker::Number.number(digits: 10) }
end
end
routes.rb
Rails.application.routes.draw do
resources :todos do
resources :items
end
end
我想这是一个相对简单的修复程序,但是我是工厂机器人的新手,我很犹豫要遵循一些可能的解决方案,因为它们会改变很多东西。如果有人有解决方案,我很想知道否则,我将继续尝试研究factorybot文档,这不是最糟糕的事情。
我认为问题出在这里:
items.rb
FactoryBot.define do
factory :item do
name { Faker::Starwars.character }
done { false }
todo_id nil
end
end
我将其更改为:
FactoryBot.define do
factory :item do
name { Faker::Lorem.character }
done { false }
todo_id { 1 }
end
end
是Lorem而不是Starwars,因为我收到此错误:uninitialized constant Faker::StarWars
我给todo_id
的值是1,这feels错误。但是,直到我找到更好的解决方案为止……它已经通过了测试。