我有两个 ActiveRecord 模型 User 和 posts。这是我的用户模型。
class User < ActiveRecord::Base
has_many :posts
end
这是我的 Post 模型。
class Post < ActiveRecord::Base
belongs_to :user
after_initialize :set_name
private
def set_name
self.name = "Post #{self.user.posts.count + 1}"
end
end
这一切都很好,但是当我写我的工厂时
FactoryGirl.define do
factory :post do
content 'blah blah'
user
end
factory :user do
name 'Dummy name'
end
end
这是我的 post_spec.rb 文件
require 'rails_helper'
RSpec.describe Post do
context 'with valid values' do
it 'should be valid' do
expect(build(:post)).to be_valid
end
end
end
我的测试用例没有说明这一点
undefined method posts for nil class in set_name
我不知道我哪里错了。
最佳答案
patkoperwas 是正确的,您试图在拥有关联的 User 对象之前初始化 Post,而您的 after_initialize 需求首先存在。如果您必须使用 after_initialize,您可以创建一个工厂,在创建 Post 之前创建一个 User,然后用它来构建。
FactoryGirl.define do
factory :user do
name "blah blah"
factory :user_with_posts do
transient do
post_count = 1
end
after(:create) do |user, evaluator|
evaluator.post_count.times do
create :post, user: user
end
end
end
end
end
我不相信 FactoryGirl 中内置了 before(:build) 功能。因此,在构建 Post 对象之前,您不能真正使用回调来创建 User 。我会创建一个 user_with_post 或显式创建一个用户并在创建帖子对象时将其传入。
RSpec.describe Post do
context 'with valid values' do
it 'should be valid' do
user = FactoryGirl.create :user_with_posts
post = user.posts.first
expect(post).to be_valid
end
end
关于ruby-on-rails - 初始化后的工厂女孩,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39149190/