此特定测试试图为用户创建“状态更新”。
这是完整的错误:
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
谢谢!