【问题标题】:Rspec SystemStackError stack level too deepRspec SystemStackError 堆栈级别太深
【发布时间】:2016-09-10 05:33:12
【问题描述】:

我正在使用 Ruby on Rails 开发一个 API。我为 posts_controller.rb 创建了一些规​​范,但在运行规范时出现此错误

SystemStackError: stack level too deep
./app/controllers/api/v1/posts_controller.rb:10:in `show'
./spec/controllers/api/v1/posts_controller_spec.rb:8:in `block (3 levels) in <top (required)>'

这是我的posts_controller_spec.rb

require 'spec_helper'

describe API::V1::PostsController do
  describe "GET #show" do
    before(:each) do
      @post = FactoryGirl.create :post
      get :show, id: @post.id
    end

    it "returns the information about a post on a hash" do
      post_response = json_response[:post]
      expect(post_response[:description]).to eql @post.description
    end

    it "has the user as a embeded object" do
      post_response = json_response[:post]
      expect(post_response[:user][:email]).to eql @post.user.email
    end

    it { expect(response.status).to eql 200 }
  end
  .
  .
  .

这是我的posts_controller.rb

class API::V1::PostsController < ApplicationController
  respond_to :json

  def show
    respond_with Post.find(params[:id])
  end

  .
  .
  .

有人有解决这个问题的想法吗?

我意识到这是导致错误的行,有人知道为什么吗?在post_serializer.rb 文件中我有这个

class PostSerializer < ActiveModel::Serializer
  attributes :id, :description, :price, :published
  has_one :user # this is the line !!!
end 

如果我删除此行,问题将得到解决,但有人知道为什么吗?

【问题讨论】:

  • json_response 是做什么的?还有,工厂有什么不寻常的地方吗?
  • json_response 是一个辅助方法,它返回: JSON.parse(response.body, symbolize_names: true)
  • 用户序列化程序中有has_many :posts 吗?如果你有它,那和后序列化程序中的has_one :user 很可能是堆栈级别太深错误的原因。
  • 请展示你的factory_girl stab和model
  • 我怀疑@RomanKovtunenko 是在正确的轨道上。你的post 工厂可能会调用你的user 工厂,它可能会调用你的post 工厂,然后它会调用你的user 工厂,等等。无限

标签: ruby-on-rails ruby ruby-on-rails-3 rspec


【解决方案1】:

您的序列化器中有一个循环引用:帖子尝试序列化其用户,但用户序列化器序列化用户帖子,然后序列化用户等。

在 active_model_serializers 0.9.x 中有一个冗长的github issue 关于这个问题。这个问题显然在 0.10 中得到修复,尽管这似乎与 rails 3.x 不兼容

一种常见的技术似乎是拥有两个版本的用户序列化程序:一个包含帖子,一个不包含帖子。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-05
    • 2014-10-25
    • 2017-08-19
    • 1970-01-01
    • 2012-01-07
    • 1970-01-01
    相关资源
    最近更新 更多