【问题标题】:NameError: undefined local variable or method `post' for #<FactoryGirl.RspecNameError:#<FactoryGirl.Rspec 的未定义局部变量或方法“post”
【发布时间】:2015-01-15 15:33:07
【问题描述】:

我尝试重构我的规范。我有视图 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>

如何解决?

对不起我的英语不好

【问题讨论】:

  • create_list(:comment, post: post)。那里的局部变量post 是什么?应该是:post
  • create_list(:comment, post: create(:post)) 应该是这样的让你拥有post factory

标签: ruby-on-rails rspec factory


【解决方案1】:

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

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

【讨论】:

  • 谢谢你的回答,但是shell呈现另一个错误。 NoMethodError:#<0x000000083c1da8>
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-08-19
  • 1970-01-01
  • 2016-02-14
  • 2016-04-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多