我是测试新手,不知道为什么会失败:
我有一个测试
require 'spec_helper'
require 'cancan/matchers'
describe User do
subject(:user) { User.create!(email: 'test@test.com', password: '12345678', password_confirmation: '12345678', goal_id: '1', experience_level_id: '1', gender: 'Female') }
it "should be valid with a name, goal, password, password_confirmation, experience_level, and gender" do
user.should be_valid
end
我认为这应该通过。我可以通过站点前端创建用户,但收到以下失败消息:
1) User should be valid with a name, goal, password, password_confirmation, experience_level, and gender
Failure/Error: subject(:user) { User.create!(email: 'test@test.com', password: '12345678', password_confirmation: '12345678', goal_id: '1', experience_level_id: '1', gender: 'Female') }
RuntimeError:
Called id for nil, which would mistakenly be 4 -- if you really wanted the id of nil, use object_id
# ./app/models/user.rb:32:in `add_initial_program'
# ./spec/models/user_spec.rb:5:in `block (2 levels) in <top (required)>'
# ./spec/models/user_spec.rb:13:in `block (2 levels) in <top (required)>'
编辑:
添加用户模型:
class User < ActiveRecord::Base
devise :database_authenticatable, :registerable, :omniauthable,
:recoverable, :rememberable, :trackable, :validatable, :token_authenticatable
before_save :ensure_authentication_token
attr_accessible :email, :password, :password_confirmation, :remember_me, :goal_id, :experience_level_id, :gender, :role, :name, :avatar, :remote_avatar_url, :authentication_token, :measurement_units
validates :goal_id, presence: :true
validates :experience_level_id, presence: :true
validates :gender, presence: :true
before_create :add_initial_program, :assign_initial_settings
protected
def add_initial_program
prog_id = Program.for_user(self).first.id
self.user_programs.build( :cycle_order => 1, :group_order => 1, :workout_order => 1, :program_id => prog_id)
end
第 32 行是:prog_id = Program.for_user(self).first.id
和被引用的方法:
def self.for_user(user)
where(:goal_id => user.goal_id, :experience_id => user.experience_level_id, :gender => user.gender)
end