【问题标题】:Rails 3 Validation Question (Rspec)Rails 3 验证问题 (Rspec)
【发布时间】:2011-06-24 01:20:51
【问题描述】:

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

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

型号

class ExerciseSet < ActiveRecord::Base

  TYPES = %w[time rep]

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

end

规格文件

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)>'

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 rspec rspec2


    【解决方案1】:

    首先,为什么实例无效?我会在规范中添加一些调试:

    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
    

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

    【讨论】:

    • 好问题。感谢调试提示;我想知道该怎么做。我将使用打印语句,看看我能找到什么。仍在尝试从 Java 世界中找出这个 ruby​​/rails 的东西。
    • 感谢 Pat 提出的使用 print 语句的建议,我想通了。我从块中取出 object.new 语句,并在每次循环遍历数组时更新块中的类型字段。代码在上面的帖子中列出。我仍然很好奇为什么第一个设计失败了。
    • 模型中没有attr_accessible 调用,是吗?
    • 不,只是核心基类和验证。
    • 对于调试,我发现最好将错误包含在测试断言中:exercise_instance.errors.full_messages.join("\n").should eq("") 这样,RSpec 将打印出验证错误以及测试信息。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-23
    • 1970-01-01
    • 2011-08-01
    • 2011-12-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多