NameError: undefined local variable or method `post' for #<FactoryGirl.Rspec

NameError: undefined local variable or method `post' for #<FactoryGirl.Rspec

我尝试重构我的 specs.I 视图 spec/views/posts。html.haml_spec.rb

require 'rails_helper'

describe 'posts/show' do
  before(:each) do
    @post = assign(:post, create(:post))
    @comments = assign(:comment, Kaminari.paginate_array([
      create(:comment, post: @post)
    ]).page(1))
  end

  it 'renders attributes in <p>' do
    render
  end
end

我想将代码转移到工厂 spec/factories/posts.rb

FactoryGirl.define do

  factory :post do
    title Faker::Lorem.word
    body Faker::Lorem.paragraph


    trait :with_comments do
      after(:create) do
        create_list(:comment, post: post)
      end
    end
  end
end

但是当我 运行 FactoryGirl.create(:post, :with_comments)、shell 显示错误时

NameError: undefined local variable or method `post' for #<FactoryGirl::SyntaxRunner:0x00000003b44f08>

怎么解决?

抱歉我的英语不好

您没有将对象传递给 after_create 块。您也没有指定要创建的评论数。将您的特征更改为:

trait :with_comments do
  after(:create) do |post|
    create_list(:comment, <number_of_comments>, post: post)
  end
end