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