gpt4 book ai didi

ruby-on-rails - 状态机、模型验证和 RSpec

转载 作者:数据小太阳 更新时间:2023-10-29 07:10:49 24 4
gpt4 key购买 nike

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

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。 “推迟”是唯一似乎通过的状态。知道这里会发生什么吗?

最佳答案

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

One important caveat here is that, due to a constraint in ActiveModel's validation framework, custom validators will not work as expected when defined to run in multiple states. For example:

 class Vehicle
include ActiveModel::Validations

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

In this case, the :speed_is_legal validation will only get run for the :second_gear state. To avoid this, you can define your custom validation like so:

 class Vehicle
include ActiveModel::Validations

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

关于ruby-on-rails - 状态机、模型验证和 RSpec,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10643997/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com