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
編集:これは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
どうしたの?