我試圖使性別測試使用Rspec的模型 - 它看起來像這樣:不能獲得工作軌道這包括驗證
it "should require a valid gender" do
wrong_gender_student = @student_group.students.create!(@student_attr.merge(gender: "Zlorp"))
wrong_gender_student.should_not be_valid
end
它未能如預期:
1) Student should require a valid gender
Failure/Error: wrong_gender_student.should_not be_valid
expected #<Student id: 2, name: "Example Student", gender: "Zlorp", created_at: "2013-05-28 16:25:53", updated_at: "2013-05-28 16:25:53", student_group_id: 1> not to be valid
然而,當添加代碼,使其通過:
class Student < ActiveRecord::Base
attr_accessible :gender, :name
belongs_to :student_group
has_many :subjects
has_many :characteristics
VALID_GENDERS = %w(Male Female Transgender)
validates :gender, inclusion: { :in => VALID_GENDERS,
:message => "%{value} is not a valid gender" }
end
它仍然失敗,卻彷彿驗證測試是worki NG,但它沒有被通過 「Zlorp」 - 下面性別 '無'
1) Student should require a valid gender
Failure/Error: association_attr #this is a list of variables in spec_helper.rb
ActiveRecord::RecordInvalid:
Validation failed: Gender is not a valid gender
編輯:這裏的association_attr:
def association_attr
# User attritbutes
@user = Factory(:user)
# Student_group
@student_group = @user.student_groups.create!(@student_group_attr)
# Student_group attributes
@student_group_attr = { name: "4a" }
# Student
@student = @student_group.students.create!(@student_attr)
# Student attributes
@student_attr = { gender: "Female", name: "Example Student" }
# Subject
@subject = @student.subjects.create!(@subject_attr)
# Subject attributes
@subject_attr = { name: "English", end_date: @date }
@date = Date.today+180
# Goal
@goal = @subject.goals.create!(@goal_attr)
# Goal attributes
@goal_attr = { goal: "To unlearn the evil" }
# Characteristic
@characteristic = @student.characteristics.create!(@char_attr)
# Characteristic attributes
@char_attr = { characteristic: "Dyslexic" }
# Age_group
# For has_one associations use 'create_object'
# http://stackoverflow.com/questions/7479083/ruby-on-rails-3-has-one-association-testing
@age = @student_group.create_age!(@age_attr)
# Age attributes
@age_attr = { age: "older adults"}
end
什麼問題?
您是否添加了'attr_accessible:gender'? –
是的,編輯將包括完整的student.rb文件 – dax