使用FactoryGirl的未定义方法after_create [英] Undefined method after_create with FactoryGirl

查看:64
本文介绍了使用FactoryGirl的未定义方法after_create的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用after_create回调在FactoryGirl中定义has_many关系,就像在/spec/factories/emails.rb中那样:

I'm trying to defined a has_many relationship in FactoryGirl using the after_create callback, like so in /spec/factories/emails.rb:

FactoryGirl.define do
    factory :email do
        after_create do |email|
            email.attachments << FactoryGirl.build(:attachment)
        end
    end
end

附件是在单独的工厂/spec/factories/attachment.rb中定义的:

The attachment is defined in a seperate factory /spec/factories/attachment.rb:

FactoryGirl.define do
    factory :attachment do
        # Attach the file to paperclip
        file { fixture_file_upload(Rails.root.join('spec', 'support', 'myimage.png'), 'image/png') }
    end
end

在我的规格中使用:attachment绝对可以正常工作,因此我有信心这不是问题所在,但是当我尝试从工厂创建:email时,会抛出以下异常:

Using the :attachment in my specs works absolutely fine, so I'm confident that the factory for that is not the problem, however when I try and create an :email from the factory I get the following exception thrown:

Failure/Error: email = FactoryGirl.create(:email)
    NoMethodError:
        undefined method `after_create=' for #<Email:0x007ff0943eb8e0>

我在做什么方面有些茫然,似乎找不到其他人遇到相同的错误.

I'm at a bit of a loss as to what to do, can't seem to find any one else getting the same error.

推荐答案

FactoryGirl

FactoryGirl recently changed the syntax for callbacks. I think the following will work:

FactoryGirl.define do
  factory :email do
    after(:create) do |email|
      email.attachments << FactoryGirl.build(:attachment)
    end
  end
end

这篇关于使用FactoryGirl的未定义方法after_create的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆