开发者

factory_girl wiggin' out over associations (infinite loop, maybe?)

开发者 https://www.devze.com 2023-02-16 15:59 出处:网络
What I have now: class User < ActiveRecord::Base has_many :people end ... and... class Person < ActiveRecord::Base

What I have now:

class User < ActiveRecord::Base
   has_many :people
end

... and...

class Person < ActiveRecord::Base
   belongs_to :user
end

In 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

I want to setup the user factory to create with 1 person association, but if I uncomment that line, when I run my tests, my system hangs for quite some time, before outputting this failure:

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

What am I doing wrong here? I would like to have tests that require an association between these two models, such that (1) a User must have at least 1 person, and (2) a Person must belong to a User.

Is this a first-priority issue开发者_StackOverflow? I'll admit I'm a bit lost here...


I'm using rspec 2.5.0, factory_girl_rails 1.0.1, and rails 3.0.5.


My specs:

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:

require 'spec_helper'

describe Person do

  subject { Factory :person }

  # ...

  context "has validation, " do

    [:gender, :user].each do |attr|

      it "must have a #{ attr }" do
        subject.send "#{attr}=", nil
        subject.should_not be_valid
        subject.errors[attr].should_not be_empty
      end

    end

  end

  context "has associations, " do

    it "can have a User" do
      subject.should respond_to :user
    end

  end

end


Keep that line but remove p.association :user from your person factory.


I've since discovered Shoulda, which provides a nice rspec matchers like these:

subject.should belong_to :user
subject.should have_many :people

Which has solved my issue.

0

精彩评论

暂无评论...
验证码 换一张
取 消