您可以覆盖模型 aasm_state 设置器(或我的示例中的状态),以便它可以接受事件名称。然后我们检查它是否是一个有效的事件,然后检查转换是否有效。如果不是,我们添加正确的错误消息。
请求规范
it "should cancel" do
put "/api/ampaigns/#{@campaign.id}", {campaign: {status: "cancel"}, format: :json}, valid_session
response.code.should == "204"
end
型号规格
it "should invoke the cancel method" do
campaign.update_attribute(:status, "cancel")
campaign.canceled?.should be_true
end
it "should add an error for illegal transition" do
campaign.update_attribute(:status, "complete")
campaign.errors.should include :status
campaign.errors[:status].should == ["status cannot transition from pending to complete"]
end
it "should add an error for invalid status type" do
campaign.update_attribute(:status, "foobar")
campaign.errors.should include :status
campaign.errors[:status].should == ["status of foobar is not valid. Legal values are pending, active, canceled, completed"]
end
该模型
class Campaign < ActiveRecord::Base
include AASM
aasm column: :status do
state :pending, :initial => true
state :active
state :canceled
state :completed
# Events
event :activate do
transitions from: :pending, to: :active
end
event :complete do
transitions from: :active, to: [:completed]
end
event :cancel do
transitions from: [:pending, :active], to: :canceled
end
end
def status=(value)
if self.class.method_defined?(value)
if self.send("may_#{value}?")
self.send(value)
else
errors.add(:status, "status cannot transition from #{status} to #{value}")
end
else
errors.add(:status, "status of #{value} is not valid. Legal values are #{aasm.states.map(&:name).join(", ")}")
end
end
end