我正在尝试使用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
有什么问题?
答案 0 :(得分:0)
你的问题就是你在第一行所做的事情
@student_group.students.create!
引发错误(ActiveRecord :: RecordInvalid),因为这就是创造!当您尝试保存无效记录时。你甚至没有到达测试有效性的第二行。你需要做的是
wrong_gender_student = @student_group.students.new(@student_attr.merge(gender: "Zlorp"))
wrong_gender_student.should_not be_valid
此外,这具有不会访问数据库的优势,您不需要进行此类测试。