FactoryGirl 使用零或零而不是字符串填充类型列

FactoryGirl populates type column with zero or nil instead of string

我有一个 :topics table 和一个 type 列用于单 table 继承。我的有效主题类型之一应该是字符串 "Announcement"。当我在 topic.rb 中的验证是:

时,我不知道如何建立一个有效的工厂
validates_inclusion_of :type, in: ["Announcement"]

当我的工厂是这样的...

factory :topic
  group
  membership
  type Announcement
end

我在规范错误中得到了这个:

...type: nil... Type is not included in the list

这是我的测试:

it 'should build a valid factory' do
  topic = FactoryGirl.build(:topic)
  expect(topic).to be_valid
end

FactoryGirl 似乎喜欢 class 名称公告而不是字符串 "Announcement",因为其他测试都是这样通过的。但是当我切换到字符串时:

factory :topic
  group
  membership
  type "Announcement"
end

我得到了同样的错误,除了

type: 0 而不是 type: nil

我应该使用字符串还是 class 名称?知道为什么我的工厂得到 0/nil 值吗?

第一位评论者是对的,您不能轻易使用 Rails 中的 type 列,因为它用于单 table 继承 (STI)。

如果您坚持使用类型列,则需要禁用 STI 功能。

Rails -- use type column without STI?

您尝试过指定子类吗?

factory :topic, :class => Announcement do
  group
  membership
end

我很确定这会奏效。