簡體   English   中英

Rails SystemStackError:堆棧級別太深

[英]Rails SystemStackError: stack level too deep

我正在測試我的應用程序(Rails 5)與rspec capybara和工廠女孩我有以下錯誤...我不知道發生了什么...我是非常新的rspec我希望你能幫助我:)謝謝你

Randomized with seed 41137

An error occurred in a `before(:suite)` hook.
Failure/Error: FactoryGirl.lint

SystemStackError:
  stack level too deep

你會在下面找到我的代碼:

factories.rb

FactoryGirl.define do
  factory :event do
    name {Faker::Friends.character}
    total_price 50
    participant
  end

  factory :participant do
    first_name { Faker::Name.first_name }
    salary 900
    event
  end
end

event.rb

class Event < ApplicationRecord
  has_many  :participants, inverse_of: :event
  validates :participants, presence: true
  validates :name, presence: true, length: {minimum: 2}
  validates :total_price, presence: true


  accepts_nested_attributes_for :participants, reject_if: :all_blank, allow_destroy: true

  def total_salary
    all_salary = []
    participants.each do |participant|
      all_salary << participant.salary
    end
    return @total_salary = all_salary.inject(0,:+)
  end
end

event_spec.rb

require 'rails_helper'

describe Event do
  it { should have_many(:participants) }
  it { should validate_presence_of(:participants) }
  it { should validate_presence_of(:name) }
  it { should validate_presence_of(:total_price) }

  describe "#total_salary" do
    it "should return the total salary of the participants" do
      partcipant_1 = create(:participant, salary: 2000)
      partcipant_2 = create(:participant, salary: 3000)

      expect(partcipant_1.salary + partcipant_2.salary).to eq(5000)
    end
  end
end

編輯

在我的參與者模型中,我必須添加optional: true belongs_to :event, option: true

所以fabriciofreitag建議很好:)

我們來看看你的工廠:

FactoryGirl.define do
  factory :event do
    name {Faker::Friends.character}
    total_price 50
    participant
  end
  factory :participant do
    first_name { Faker::Name.first_name }
    salary 900
    event
  end
end

在這種情況下,事件的創建將創建一個參與者,該參與者將創建一個將創建參與者的事件。 等等,在無限循環中(堆棧級別太深)。

也許你可以把它改成這樣的東西:

FactoryGirl.define do
  factory :event do
    name {Faker::Friends.character}
    total_price 50
    participants { create_list(:participant, 3, event: self) }
  end
  factory :participant do
    first_name { Faker::Name.first_name }
    salary 900
  end
end

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM