Rails API - RSPEC工厂女孩堆栈级别太深?

时间:2014-11-10 01:33:35

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

遇到以下错误并且在堆栈级别上已经广泛阅读太深的错误。我在开发环境中使用Ruby 1.9.3-p392,Rails 4.1.4和Rspec-core 3.1.7以及factory girl rails 4.5。我发现有些人正在创造一个无限循环。所以我系统地评论了代码以查看我返回的其他错误,但我完全被卡住了。

1) POST /v1/notes/id saves the lat, lon, note text, note photo, recipients, and expiration
     Failure/Error: Unable to find matching line from backtrace
     SystemStackError:
     stack level too deep
      # /Users/njayanty/.rbenv/versions/1.9.3-p392/lib/ruby/gems/1.9.1/gems/activesupport-   4.1.4/lib/active_support/cache/strategy/local_cache_middleware.rb:33
 #
 #   Showing full backtrace because every line was filtered out.
 #   See docs for RSpec::Configuration#backtrace_exclusion_patterns and
 #   RSpec::Configuration#backtrace_inclusion_patterns for more information.

Finished in 0.52889 seconds (files took 9.32 seconds to load)
8 examples, 1 failure

这是我的规范:

describe 'POST /v1/notes/id' do
  it 'saves the lat, lon, note text, note photo, recipients, and expiration' do
    date = Time.zone.now
    devicetoken = '123abcd456xyz'
    user = create(:user, devicetoken: devicetoken)

  post '/v1/notes', {
    user_id: user.id,
    devicetoken: user.devicetoken,
    lat: 5.5,
    lon: 3.3,
    note_text: 'Hey sweetie! Just thinking about your lovely face!',
    photo_uri: 'http://www.photour/l12345.jpg',
    expiration: date,
  }.to_json, {'Content-Type' => 'application/json' }

  note = Note.last
  expect(response_json).to eq({ 'id' => note.id })
  expect(note.lat).to eq (5.5)
  expect(note.lon).to eq(3.3)
  expect(note_text).to eq('Hey sweetie! Just thinking about your lovely face!')
  expect(note.photo_uri).to eq('http://www.photour/l12345.jpg')
  expect(note.expiration.to_i).to eq date.to_i

  end
end

这是我的工厂

用户

FactoryGirl.define do
  factory :user do
    first "MyString"
    last "MyString"
    email "MyString"
    username "MyString"
    pw "MyString"
    devicetoken "MyString"
  end
end

注释

FactoryGirl.define do
  factory :note do
    user_id 1
    note_text "MyText"
    lat 1.5
    lon 1.5
    photo_uri "MyString"
    expiration Time.zone.now.utc
  end
end

这是控制器代码:

def note_params
  { 
    user_id: user.id,
    devicetoken: user.devicetoken,
    lat: params[:lat],
    lon: params[:lon],
    note_text: params[:note_text],
    photo_uri: params[:photo_uri],
    expiration: params[:expiration]
  }
end

def user
  User.find_or_create_by(user_id: user.id)
end

这里是Note模型 - 我是否需要验证设备令牌的唯一性?:

class Note < ActiveRecord::Base
  validates :user_id, presence: true
  validates :note_text, presence:true 
  validates :lat, presence: true 
  validates :lon, presence: true
  validates :expiration, presence: true

  belongs_to :user, foreign_key: 'user_id', class_name: 'User'
end

1 个答案:

答案 0 :(得分:1)

您的用户方法

def user
  User.find_or_create_by(user_id: user.id)
end

将无限递归 - 我假设您打算从params传递user_id。

find_or_create_by似乎不太可能使用正确的方法 - 通常如果您有用户ID,那么您只需使用find