3

我想使用 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

根据此处找到的文档,这就是我到目前为止所拥有的。这与我迄今取得的任何实际进展一样接近。

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)

谢谢!

4

2 回答 2

6

对我来说,看起来你必须为和through建立has_many关联。这看起来像RegistrationsUsersUserRegistrations

    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
于 2013-07-18T20:27:57.443 回答
0

我想我之前经历过这个问题(不太明显你会同意这一点)你在工厂定义中使用了一个常量名称。

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

factory :user, class: 'User' do
  ...
于 2013-07-16T01:16:52.347 回答