简体   繁体   English

Rspec SystemStackError堆栈级别太深

[英]Rspec SystemStackError stack level too deep

I'm developing an API using Ruby on Rails. 我正在使用Ruby on Rails开发API。 I've created some specs for posts_controller.rb and I'm having this error while running the specs 我已经为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)>'

This is my posts_controller_spec.rb 这是我的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
  .
  .
  .

This is my posts_controller.rb 这是我的posts_controller.rb

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

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

  .
  .
  .

Anybody have ideas to solve this problem ? 有人有解决这个问题的想法吗?

I realized that this is the line that causes the error, anyone know why? 我意识到这是导致错误的行,有人知道为什么吗? In post_serializer.rb file I have this post_serializer.rb文件中,我有这个

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

If I remove this line the problem will be fixed, but anyone knows why ? 如果我删除此行,问题将得到解决,但是谁知道为什么?

You have a circular reference in your serialiser: the post tries to serialise its user, but the user serializer serializes the users posts, which then serialise the user etc. 您在序列化程序中有一个循环引用:帖子尝试序列化其用户,但是用户序列化程序将对用户帖子进行序列化,然后对用户进行序列化等。

There is a lengthy github issue about this issue in active_model_serializers 0.9.x. 在active_model_serializers 0.9.x中有一个关于此问题的冗长的github问题。 The issue is apparently fixed in 0.10, although that doesn't appear to be compatible with rails 3.x 这个问题显然在0.10中已解决,尽管似乎与rails 3.x不兼容。

A common technique appears to be to have 2 versions of the user serializer: one which includes posts and one which does not. 一种常见的技术似乎是具有两个版本的用户序列化程序:一个包含帖子,另一个不包含。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM