我正在尝试使用 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
它仍然失败,似乎验证测试正在工作,但没有通过“Zlorp” - 下面的性别是“Nil”
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
编辑:这里是关联属性:
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
有什么问题?