0

我的工厂:

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 assignment 创建了一个新的用户记录?提前致谢。

4

1 回答 1

1

原因是你的 let for commentcalls Factory.create :comment。在工厂 for 中comment,它调用关联 for user

因此,当您使用 let 时,它会创建一个评论对象和一个用户对象并将它们连接起来。然后,您在设置时覆盖该用户comment.user=user

于 2012-06-07T18:14:22.650 回答