【问题标题】:Rails Factory Girl with Circular Relation有循环关系的 Rails 工厂女孩
【发布时间】:2014-06-09 07:19:51
【问题描述】:

我有两个具有循环关系的模型。如何在 Factory Girl 中为这些建模?

我收到太多错误消息,正在尝试这样做。

型号:

class Account < ActiveRecord::Base
  has_many :users
  belongs_to :owner, class_name: "User", inverse_of: :account
end

class User < ActiveRecord::Base
  belongs_to :account
end

工厂:

FactoryGirl.define do
  factory :user, aliases: [:owner] do
    sequence(:email) { |n| "user#{n}@example.com" }
    password "test"
    password_confirmation "test"
    account
  end
end

FactoryGirl.define do
  factory :account do |account|
    account.name "My School"
    account.short_name "school1"
    account.sequence(:subdomain) { |n| "school#{n}" }
    account.owner { FactoryGirl.build(:user, account: account) }
  end
end

我收到以下错误:

 Failure/Error: let!(:user) { FactoryGirl.create(:user) }
 NoMethodError:
   undefined method `primary_key' for #<FactoryGirl::Declaration::Implicit:0x00000007bd9050>
 # ./spec/factories/accounts.rb:8:in `block (3 levels) in <top (required)>'
 # ./spec/models/user_spec.rb:8:in `block (3 levels) in <top (required)>'
 # -e:1:in `<main>'

你能帮忙解决这个错误吗?

【问题讨论】:

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


    【解决方案1】:

    试试这个

    FactoryGirl.define do
      factory :user do
        sequence(:email) { |n| "user#{n}@example.com" }
        password "test"
        password_confirmation "test"
        association :account
      end
    end
    
    FactoryGirl.define do
      factory :account do
        name "My School"
        short_name "school1"
        sequence(:subdomain) { |n| "school#{n}" }
        association :owner, factory: :user
      end
    end
    

    【讨论】:

    • 我得到堆栈太深的错误:Failure/Error: Unable to find matching line from backtrace SystemStackError: stack level too deep
    • 哇! - 更新的答案,在association :owner, factory: :user 上缺少:
    • 是的。我在测试之前添加了这一点
    • @ZiaUlRehmanMughal 为什么会这样?存在循环依赖。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多