2013-05-28 48 views
0

我試圖使性別測試使用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 

什麼問題?

+0

您是否添加了'attr_accessible:gender'? –

+0

是的,編輯將包括完整的student.rb文件 – dax

回答

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 

此外,這有沒有擊中數據庫,你不需要這種測試的優勢。

+0

仍然有同樣的錯誤 - 編輯包括association_attr萬一有錯誤的情況下。謝謝! – dax

+0

拿出了創建!在association_attr中,並修復它。乾杯! – dax