【问题标题】:Undefined method after_create with FactoryGirl使用 FactoryGirl 的未定义方法 after_create
【发布时间】:2013-02-21 13:51:28
【问题描述】:

我正在尝试使用 after_create 回调在 FactoryGirl 中定义 has_many 关系,就像在 /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 中定义:

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 时,会抛出以下异常:

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

我有点不知所措,似乎找不到其他人遇到同样的错误。

【问题讨论】:

    标签: ruby-on-rails-3 rspec factory-bot


    【解决方案1】:

    FactoryGirl recently changed 回调的语法。我认为以下方法会起作用:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-01
      • 1970-01-01
      相关资源
      最近更新 更多