工厂女孩未定义的nil方法:NilClass

时间:2013-10-31 01:49:44

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

我有一个像这样的控制器规范

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

3 个答案:

答案 0 :(得分:0)

这应该有效。测试数据库不正确的所有要点。

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

答案 1 :(得分:0)

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

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

我没有在Fabricator文档中看到一个完全像我需要的例子,但我用这种语法得到了它:

Fabricator(:my_class)做   on_init做     init_with(“公司名称”,“假第二档”)   结束 端

答案 2 :(得分:0)

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