如何使用 FactoryBot 修复 rspec 测试中的 'undefined method' 枚举?
How to fix 'undefined method' enum in rspec test with FactoryBot?
我正在尝试测试我为我的应用程序创建的模型,它与其他两个模型有关联,也使用 Factory Bot 构建测试,但它无法识别它,错误 return 是:Failure/Error: status :pending //// NoMethodError: undefined method 'status' in 'pending' factory.
我是 运行 应用程序 Ruby 2.6.1,Rails 5.2.3,FactoryBot 5.0.2,Rspec 3.8。我尝试了不同的方法来定义枚举。我不知道该怎么办了。
型号:
class CollegeWhitelist < ApplicationRecord
enum status: {pending: 0, approved: 1, rejected: 2}
has_many :users
has_many :colleges
end
工厂:
FactoryBot.define do
factory :college_whitelist do
association :user
association :college
trait :pending do
status :pending
end
trait :approved do
status :approved
end
trait :rejected do
status :rejected
end
end
end
Rspec:
require 'rails_helper'
RSpec.describe CollegeWhitelist, type: :model do
describe "#consistency " do
it 'cannot insert the same user for the same college in permissions' do
@permission = build(:college_whitelist)
p @permission
end
end
end
一开始我只是希望它能通过打印对象的测试。
这是命名冲突的问题。
您必须将 status
列的值括在花括号中,否则它会调用自身:
FactoryBot.define do
factory :college_whitelist do
...
trait :pending do
status { :pending }
end
trait :approved do
status { :approved }
end
trait :rejected do
status { :rejected }
end
end
end
我正在尝试测试我为我的应用程序创建的模型,它与其他两个模型有关联,也使用 Factory Bot 构建测试,但它无法识别它,错误 return 是:Failure/Error: status :pending //// NoMethodError: undefined method 'status' in 'pending' factory.
我是 运行 应用程序 Ruby 2.6.1,Rails 5.2.3,FactoryBot 5.0.2,Rspec 3.8。我尝试了不同的方法来定义枚举。我不知道该怎么办了。
型号:
class CollegeWhitelist < ApplicationRecord
enum status: {pending: 0, approved: 1, rejected: 2}
has_many :users
has_many :colleges
end
工厂:
FactoryBot.define do
factory :college_whitelist do
association :user
association :college
trait :pending do
status :pending
end
trait :approved do
status :approved
end
trait :rejected do
status :rejected
end
end
end
Rspec:
require 'rails_helper'
RSpec.describe CollegeWhitelist, type: :model do
describe "#consistency " do
it 'cannot insert the same user for the same college in permissions' do
@permission = build(:college_whitelist)
p @permission
end
end
end
一开始我只是希望它能通过打印对象的测试。
这是命名冲突的问题。
您必须将 status
列的值括在花括号中,否则它会调用自身:
FactoryBot.define do
factory :college_whitelist do
...
trait :pending do
status { :pending }
end
trait :approved do
status { :approved }
end
trait :rejected do
status { :rejected }
end
end
end