【问题标题】:State Machine, Model Validations and RSpec状态机、模型验证和 RSpec
【发布时间】:2012-05-17 21:48:41
【问题描述】:

这是我当前的类定义和规范:

class Event < ActiveRecord::Base

  # ...

  state_machine :initial => :not_started do

    event :game_started do
      transition :not_started => :in_progress
    end

    event :game_ended do
      transition :in_progress => :final
    end

    event :game_postponed do
      transition [:not_started, :in_progress] => :postponed
    end

    state :not_started, :in_progress, :postponed do
      validate :end_time_before_final
    end
  end

  def end_time_before_final
    return if end_time.blank?
    errors.add :end_time, "must be nil until event is final" if end_time.present?
  end

end

describe Event do
  context 'not started, in progress or postponed' do
    describe '.end_time_before_final' do
      ['not_started', 'in_progress', 'postponed'].each do |state|
        it 'should not allow end_time to be present' do
          event = Event.new(state: state, end_time: Time.now.utc)
          event.valid?
          event.errors[:end_time].size.should == 1
          event.errors[:end_time].should == ['must be nil until event is final']
        end
      end
    end
  end
end

当我运行规范时,我得到了两次失败和一次成功。我不知道为什么。对于其中两个状态,end_time_before_final 方法中的 return if end_time.blank? 语句在每次都应该为 false 时评估为 true。 “推迟”是唯一似乎通过的状态。知道这里可能会发生什么吗?

【问题讨论】:

  • before_transition :on =&gt; :game_ended 似乎不完整
  • 这些对象在您失败的规范中是否有效?
  • 删除了 before_transition。其中两个对象对 :end_time 有效,一个对 :end_time 有效。

标签: ruby-on-rails ruby rspec state


【解决方案1】:

您似乎遇到了documentation 中提到的警告:

这里有一个重要的警告是,由于 ActiveModel 验证的限制 框架,自定义验证器在定义运行时将无法按预期工作 在多个州。例如:

 class Vehicle
   include ActiveModel::Validations

   state_machine do
     ...
     state :first_gear, :second_gear do
       validate :speed_is_legal
     end
   end
 end

在这种情况下,:speed_is_legal 验证只会运行 对于 :second_gear 状态。为避免这种情况,您可以定义您的 像这样的自定义验证:

 class Vehicle
   include ActiveModel::Validations

   state_machine do
     ...
     state :first_gear, :second_gear do
       validate {|vehicle| vehicle.speed_is_legal}
     end
   end
 end

【讨论】:

  • 甜蜜!付费阅读。谢谢你比我更细心。
猜你喜欢
  • 2012-05-03
  • 1970-01-01
  • 1970-01-01
  • 2020-05-17
  • 1970-01-01
  • 1970-01-01
  • 2023-04-07
  • 2020-05-22
相关资源
最近更新 更多