2011-06-24 78 views
0

完全被这个难住了。我发誓,这看起来应该工作,但它没有。测试数据库已更新(rake db:migrate - rake:db:test:clone)。我希望我做一些愚蠢的事情。Rails 3验证问题(Rspec)

完全披露,我正在运行3.1 RC4。

型号

class ExerciseSet < ActiveRecord::Base 

    TYPES = %w[time rep] 

    validates :type, 
      :presence => true, 
      :inclusion => { :in => TYPES } 

end 

SPEC文件

require 'spec_helper' 

describe ExerciseSet do 

    before(:each) do 
    @attr = { :value => 12, 
       :value_max => 15, 
       :type => "timed", 
       :target => "range" 
    }    
    end 


    describe "type" do 
    it "must be either 'time' or 'rep'" do 
     values = %w[time rep] 
     values.each do |value| 
     exercise_instance = ExerciseSet.new(@attr.merge(:type => value)) 
     exercise_instance.should be_valid 
     end 
    end 
    end 

end 

输出

Failures: 

    1) ExerciseSet type must be either 'time' or 'rep' 
    Failure/Error: exercise_instance.should be_valid 
     expected valid? to return true, got false 
    # ./spec/models/exercise_set_spec.rb:19:in `block (4 levels) in <top (required)>' 
    # ./spec/models/exercise_set_spec.rb:17:in `each' 
    # ./spec/models/exercise_set_spec.rb:17:in `block (3 levels) in <top (required)>' 

回答

0

首先第一件事情 - 为什么不是实例有效吗?我会加入一些调试规范:

describe "type" do 
    it "must be either 'time' or 'rep'" do 
    values = %w[time rep] 
    values.each do |value| 
     exercise_instance = ExerciseSet.new(@attr.merge(:type => value)) 
     exercise_instance.valid? # force errors 
     puts exercise_instance.errors.full_messages.join("\n") 
     exercise_instance.should be_valid 
    end 
    end 
end 

是的,这也许应该是一个评论,但我不能那么容易提供规范重写。

+0

伟大的问题。感谢您的调试提示;我想知道如何做到这一点。我会玩打印报告,看看我能找到什么。仍然试图从Java世界中发现这个ruby/rails的东西。 – bballer320xu

+0

感谢Pat的使用打印语句的建议,我想到了这一点。我从块中取出object.new语句,并在每次循环数组时更新块中的类型字段。代码在上面的帖子中列出。尽管如此,我还是很好奇为什么第一个设计失败了。 – bballer320xu

+0

你在模型中没有'attr_accessible'调用,是吗? – pat