Bạn có thể ghi đè lên các mô hình aasm_state setter (hoặc trạng thái trong ví dụ của tôi) để nó có thể chấp nhận tên sự kiện. Sau đó, chúng tôi kiểm tra xem đó có phải là sự kiện hợp lệ không, sau đó kiểm tra xem liệu quá trình chuyển đổi có hợp lệ hay không. Nếu họ không phải là chúng tôi thêm thông báo lỗi chính xác.
Một yêu cầu đặc tả
it "should cancel" do
put "/api/ampaigns/#{@campaign.id}", {campaign: {status: "cancel"}, format: :json}, valid_session
response.code.should == "204"
end
Model Spec
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
Mô hình
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
lưu ý rằng trong trường hợp này, bạn có thể không có một sự chuyển đổi từ trạng thái "x" để " được xuất bản "và AASM sẽ tăng ngoại lệ. Nếu không, âm thanh hợp lý. Boy, tôi là một người sáng lập nitpicker sáng nay: P – jaydel
Phải, đây là mã giả. Điều này chỉ có nghĩa là minh họa một mô hình chung. – Wukerplank