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 を返します。しかし、2 回目の binding.pry では、User.countは 2 を返します。私の質問は、なぜcomment.user = user割り当てが新しいユーザー レコードを作成するのかということです。前もって感謝します。

4

1 に答える 1

1

その理由は、comment呼び出しを許可するためFactory.create :commentです。のファクトリでcommentは、 の関連付けを呼び出しますuser

したがって、let を使用すると、コメント オブジェクトとユーザー オブジェクトが作成され、それらが接続されます。次に、設定時にそのユーザーをオーバーライドしますcomment.user=user

于 2012-06-07T18:14:22.650 に答える