无法使用FactoryBot在Rspec中建立has_and_belongs_to_many关系

时间:2018-10-22 22:01:00

标签: ruby-on-rails ruby rspec factory-bot

我在这里阅读FactoryBot的文档:https://www.rubydoc.info/gems/factory_bot/file/GETTING_STARTED.md

我有用户和角色,这是一个has_and_belongs_to_many关系。我尝试了文档中的许多步骤来建立这种关系,但是没有任何效果。

首先,我尝试了这种技术:

FactoryBot.define do
  factory :role do
    name { "marketing" }

    factory :admin_role do
      name { "admin" }
    end
  end
end

FactoryBot.define do
  factory :user, aliases: [:marketing] do
    email { 'marketing@mysite.io' }
    password { '123456' }
    password_confirmation { '123456' }
    association :role
  end
end

但这给了我

NoMethodError: undefined method `role=' for #<User:0x007f9743449198>

第二,我尝试了这种技术:

FactoryBot.define do
  factory :role do
    name { "marketing" }

    factory :admin_role do
      name { "admin" }
    end
  end
end

FactoryBot.define do
  factory :user, aliases: [:marketing] do
    email { 'marketing@mysite.io' }
    password { '123456' }
    password_confirmation { '123456' }
    role
  end
end

但我再次收到此错误:

NoMethodError: undefined method `role=' for #<User:0x007f9743449198>

第三,我尝试了使关系多元的这种技术:

FactoryBot.define do
  factory :role do
    name { "marketing" }

    factory :admin_role do
      name { "admin" }
    end
  end
end

FactoryBot.define do
  factory :user, aliases: [:marketing] do
    email { 'marketing@mysite.io' }
    password { '123456' }
    password_confirmation { '123456' }
    role
  end
end

我收到此错误:

ArgumentError: Trait not registered: roles

但是,当我阅读文档时,它表明我可以使用这些方法。那我在做什么错了?

1 个答案:

答案 0 :(得分:0)

不确定是否可以使用,但是由于用户可以具有多个角色,因此您可能需要将一个角色添加为单个数组项

FactoryBot.define do
  factory :user, aliases: [:marketing] do
    email { 'marketing@mysite.io' }
    password { '123456' }
    password_confirmation { '123456' }
    roles { [ role ] }
  end
end

FactoryBot.define do
  factory :user, aliases: [:marketing] do
    email { 'marketing@mysite.io' }
    password { '123456' }
    password_confirmation { '123456' }
    roles { [ create(role) ] }
  end
end

发生错误的原因是您无法致电@user.role,但可以通过HABTM关系致电@user.roles