FactoryGirl创建一个额外的对象

时间:2012-06-07 18:05:47

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

我的工厂:

FactoryGirl.define do
  factory :comment do
    content 'bla bla bla bla bla'
    user
  end

  factory :user do
    sequence(:username) { |n| "johnsmith#{n}" }
    password '123'

    factory :user_with_comments do
      ignore do
        comments_count 5
      end

      after(:create) do |user, evaluator|
        FactoryGirl.create_list(:comment, evaluator.comments_count, user: user)
      end
    end
  end
end

我的规格:

require 'spec_helper'

describe Comment do
  let(:comment) { Factory.create :comment }

  describe "Attributes" do
    it { should have_db_column(:content).of_type(:text) }
    it { should have_db_column(:user_id).of_type(:integer) }
    it { should have_db_column(:profile_id).of_type(:integer) }
  end

  describe "Relationships" do
    it { should belong_to(:profile) }
    it { should belong_to(:user)    }
  end

  describe "Methods" do
    describe "#user_name" do
      it "Should return the comment creater username" do
        user         = Factory.create :user
        binding.pry
        comment.user = user
        binding.pry
        comment.user_username.should == user.username
      end
    end
  end
end

在第一个binding.pry上, User.count 按预期返回1。但是在第二个binding.pry上, User.count 返回2.我的问题是,为什么 comment.user = user 分配会创建一个新的用户记录?提前谢谢。

1 个答案:

答案 0 :(得分:1)

原因是您允许comment来电Factory.create :comment。在comment的工厂中,它会调用user的关联。

因此,当您使用let时,它会创建一个注释对象和一个用户对象并连接它们。然后,在设置comment.user=user

时覆盖该用户