我现在拥有的:
class User < ActiveRecord::Base
has_many :people
end
......和......
class Person < ActiveRecord::Base
belongs_to :user
end
在spec/factories.rb
:
Factory.define :user do |u|
u.email "test@test.com"
u.password "testpassword"
u.password_confirmation "testpassword"
u.display_name "neezer"
# u.people { |i| [i.association(:person)] }
end
Factory.define :person do |p|
p.first_name "p_firstname"
p.last_name "p_lastname"
p.gender "male"
p.association :user
end
我想将用户工厂设置为使用1人关联创建,但是如果我取消注释该行,当我运行测试时,系统会挂起很长一段时间,然后输出此错误:
1) User can be created from a factory
Failure/Error: Unable to find matching line from backtrace
SystemStackError:
stack level too deep
# /Users/test/.rvm/gems/ruby-1.9.2-p0/gems/activerecord-3.0.5/lib/active_record/persistence.rb:285
我在这里做错了什么?我希望测试需要这两个模型之间的关联,这样(1)User
必须至少有1个人,(2)Person
必须属于{{1 }}
这是首要问题吗?我承认我在这里有点迷失......
我正在使用User
,rspec 2.5.0
和factory_girl_rails 1.0.1
。
我的规格:
rails 3.0.5
:
user_spec.rb
require 'spec_helper'
describe User do
subject { Factory :user }
# ...
context "has associations, " do
it "can have people" do
subject.should respond_to :people
end
it "must have at least 1 person" do
subject.send "people=", nil
subject.should_not be_valid
subject.errors[:people].should_not be_empty
end
end
end
:
person_spec.rb
答案 0 :(得分:1)
保留该行,但从您的工厂中删除p.association :user
。
答案 1 :(得分:0)
我发现了Shoulda,它提供了一个很好的rspec匹配器:
subject.should belong_to :user
subject.should have_many :people
这解决了我的问题。