factory_girl(4.2.0)多对多的关系

时间:2013-07-15 20:34:24

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

我想使用FactoryGirl 4.2.0正确建立多对多工厂集。我继续使用以前的FactoryGirl版本混合在一起的过时语法的文档/示例,它对我不起作用。

如何根据以下两个资源及其链接表设置此方案:

class User < ActiveRecord::Base
  has_many :user_registrations
  has_many :registrations, through: :user_registrations
end

class UserRegistration < ActiveRecord::Base
  belongs_to :user
  belongs_to :registration
end

class Registration < ActiveRecord::Base
  has_many :user_registrations
  has_many :users, through: :user_registrations
end

根据文档found here,这是我到目前为止所做的。这就像我到目前为止所取得的任何实际进展一样接近。

FactoryGirl.define do

  factory :registration do
    user
  end

  factory :user, class: User do
    sequence(:email) { |n| "foo#{n}@example.com" }
    password "password"

    factory :user_with_registrations do

      ignore do
        registrations_count 1
      end

      after(:create) do |user, evaluator|
        registrations FactoryGirl.create_list(:registration, evaluator.registrations_count, user: user)
      end
    end
  end
end

以下列方式失败,我意识到这是因为这种设置被认为是一对多的关系。

1) User Login Success
     Failure/Error: user = FactoryGirl.create(:user_with_registrations)
     NoMethodError:
       undefined method `user=' for #<Registration:0x007fc48e2ca768>
     # ./spec/factories.rb:18:in `block (4 levels) in <top (required)>'

使用最新的FactoryGirl语法为多对多场景定义工厂集的正确方法是什么? (4.2.0)

谢谢!

2 个答案:

答案 0 :(得分:6)

对我来说,您似乎必须通过has_manyRegistrationsUsers建立UserRegistrations关联。这看起来像

    factory :user_registration do
       association :user
       association :registration
    end

    factory :user do
       ..setup for email and password

       factory :user_with_registrations do

          ignore do
            registrations_count 1
          end

          after(:create) do |user, evaluator|
            FactoryGirl.create_list(:user_registration, evaluator.registrations_count, user: user)
          end
       end
    end

    factory :registration do
       ..setup for registration

       factory :registration_with_user do

          ignore do
            users_count 1
          end

          after(:create) do |registration, evaluator|
            FactoryGirl.create_list(:user_registration, evaluator.users_count, registration: registration)
          end
       end
    end

答案 1 :(得分:0)

我认为我之前已经完成了这个问题,而且你的工厂定义中使用了一个常量名称,问题(不太明显你会同意)。

尝试使用字符串,如下所示:

factory :user, class: 'User' do
  ...