2011-06-24 75 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