NoMethodError:nil的未定义方法`*':NilClass Factory Girl / Capybara问题

时间:2012-09-11 14:28:36

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

此特定测试正在尝试为用户创建“状态更新”。

以下是完整错误:

 Failure/Error: FactoryGirl.create(:status_update, user: @user, created_at: 1.day.ago)
 NoMethodError:
   undefined method `*' for nil:NilClass
 # ./app/models/status_update.rb:31:in `default_values'
 # ./spec/models/user_spec.rb:28:in `block (3 levels) in <top (required)>'

以下是测试:

describe "Status Update Associations" do
before { @user.save }
let!(:older_status_update) do 
  FactoryGirl.create(:status_update, user: @user, created_at: 1.day.ago)
end
let!(:newer_status_update) do 
  FactoryGirl.create(:status_update, user: @user, created_at: 1.hour.ago )
end

it "should have status updates in the right order" do 
  @user.status_update.should == [newer_status_update, older_status_update]
end
end     

由于错误指向状态更新模型,我也可以在此处包含它。我怀疑它与初始化和let之后设置的一些变量有关!在测试中,虽然我很难尝试不同的回调。

class StatusUpdate < ActiveRecord::Base
   belongs_to :user

   after_initialize :default_values

   attr_accessible :current_weight,
                   :current_bf_pct,
                   :current_lbm,
                   :current_fat_weight,
                   :change_in_weight,
                   :change_in_bf_pct,
                   :change_in_lbm,
                   :change_in_fat_weight,
                   :total_weight_change,
                   :total_bf_pct_change,
                   :total_lbm_change,
                   :total_fat_change

   validates :user_id, presence: true
   validates :current_bf_pct, presence: true,
                              numericality: true,
                              length: { minimum: 4, maximum:5 }  
   validates :current_weight, presence: true,
                              numericality: true,
                              length: { minimum: 4, maximum:5 } 
   validates :current_lbm, presence: true
   validates :current_fat_weight, presence: true                   

   def default_values
     self.current_fat_weight = self.current_weight * self.current_bf_pct
     self.current_lbm = self.current_weight - self.current_fat_weight
   end  

   default_scope order: 'status_update.created_at DESC'
end         

以下是将'current_weight和current_bf_pct添加到default_values方法的工厂。

 factory :status_update do
user
  current_weight 150
  current_bf_pct 0.15
end         

谢谢!

1 个答案:

答案 0 :(得分:1)

这是由于您的default_values方法。

你正在做self.current_weight * self.current_bf_pct,但没有一个被设置为数值。