【问题标题】:Factory Girl undefined method for nil:NilClass工厂女孩未定义的 nil 方法:NilClass
【发布时间】:2013-10-31 01:49:43
【问题描述】:

我有一个类似这样的控制器规格

describe :bizzaro_controller do

  let(:credit_card_account) { FactoryGirl.build :credit_card_account }

  it "doesn't blow up with just the stub" do
    CreditCardAccount.stub(:new).and_return(credit_card_account)
  end

  it "doesn't blow up" do
    credit_card_account
    CreditCardAccount.stub(:new).and_return(credit_card_account)
  end

end

结果如下:

bizzaro_controller
  doesn't blow up with just the stub (FAILED - 1)
  doesn't blow up

Failures:

  1) bizzaro_controller doesn't blow up
     Failure/Error: let(:credit_card_account) { FactoryGirl.build :credit_card_account }
     NoMethodError:
       undefined method `exp_month=' for nil:NilClass
     # ./spec/controllers/user/bizzareo_controller_spec.rb:5:in `block (2 levels) in <top (required)>'
     # ./spec/controllers/user/bizzareo_controller_spec.rb:9:in `block (3 levels) in <top (required)>'

Finished in 0.23631 seconds
2 examples, 1 failure

我的信用卡工厂是这样的:

FactoryGirl.define do
  factory :credit_card_account do
    exp_month 10
    exp_year 2075
    number '3'
  end
end

我的 CreditCardAccount 是一个空的 ActiveRecord::Base 模型

=> CreditCardAccount(id: integer, exp_month: integer, exp_year: integer, number: string)

版本

0 HAL:0 work/complex_finance % bundle show rails rspec-rails factory_girl
/home/brundage/.rvm/gems/ruby-2.0.0-p247@complex_finance/gems/rails-4.0.0
/home/brundage/.rvm/gems/ruby-2.0.0-p247@complex_finance/gems/rspec-rails-2.14.0
/home/brundage/.rvm/gems/ruby-2.0.0-p247@complex_finance/gems/factory_girl-4.2.0

【问题讨论】:

  • 在我看来一切都是合法的。您是否正确准备了测试数据库,即。 rake db:test:prepare?
  • 是的。之前做过RAILS_ENV=test rake db:wipe db:migrate db:seed。 (db:wipe 是一个自定义任务,只删除所有表)
  • 你能尝试实际运行rake db:test:prepare吗?
  • @sevenseacat 完成。没有变化。

标签: ruby-on-rails ruby factory-bot rspec2


【解决方案1】:

这应该可以工作。您的测试数据库不正确的所有点。

RAILS_ENV=test rake db:drop db:create 将删除并重新创建您的测试数据库。然后尝试使用 rake 命令运行 rspec,以迁移数据库:rake rspec

【讨论】:

  • 谢谢,但不是这样。
  • @DeanBrundage 抱歉。会让那里的答案可能帮助谷歌到这里的人。你能在你的测试数据库中看到这个列吗?你的db/schema.rb 正确吗?
  • 查看我对您的回答的回复。
【解决方案2】:

我遇到了同样的问题,但我认为问题的原因不同。不过,我的解决方案可能有用:我使用了 Fabrication gem (http://www.fabricationgem.org/) 而不是 FG。

我遇到这个问题的原因是因为我试图让 FG 创建/构建一个不是 ActiveRecord 的对象,它只是一个 ActiveModel,并且必须使用参数进行初始化。

我没有在 Fabricator 文档中看到完全符合我需要的示例,但我通过以下语法得到了它:

Fabricator(:my_class) 做 on_init 做 init_with("公司名称", "假第二个参数") 结尾 结束

【讨论】:

    【解决方案3】:

    我的问题是,我在模型中创建了一个名为 :send 的私有方法(忘记了它已经在 Ruby 中使用过)。

    【讨论】:

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