NameError:未定义的局部变量或方法`post'为#

时间:2015-01-15 15:33:08

标签: ruby-on-rails rspec factory

我尝试重构我的规格。我有查看 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>

如何解决?

抱歉我的英文不好

1 个答案:

答案 0 :(得分:1)

您没有将对象传递给after_create阻止。您也没有指定要创建的注释数。将您的特质改为:

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