使用rspec测试aasm状态转换

时间:2016-09-01 14:06:55

标签: ruby-on-rails ruby rspec state-machine aasm

我使用aasm gem来处理项目中的状态转换。我有一个看起来像这样的简单模型:

class TransferPostingBid < ActiveRecord::Base
  include AASM

  aasm :status do
    state :offered, initial: true
    state :wait_for_pap_confirmation
    state :confirmed_by_pap
    state :retracted_by_pap

    event :pap_choosed do
      transitions from: :offered, to: :wait_for_pap_confirmation
    end

    event :confirmed_by_pap do
      transitions from: :wait_for_pap_confirmation, to: :confirmed_by_pap
    end

    event :retracted_by_pap do
      transitions from: :wait_for_pap_confirmation, to: :retracted_by_pap
    end
  end
end

我尝试使用在rspec匹配器中构建的aasm来测试转换:

require 'rails_helper'

describe TransferPostingBid, type: :model do
  describe 'state transitions' do
    let(:transfer_posting_bid) { TransferPostingBid.new }

    it 'has default state' do
      expect(transfer_posting_bid).to transition_from(:offered).to(:wait_for_pap_confirmation).on_event(:pap_choosed)
    end
  end
end

当我运行此规范时,它会返回以下错误:

 AASM::UnknownStateMachineError:
   There is no state machine with the name 'default' defined in TransferPostingBid!

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:2)

您可以尝试使用#on方法指定您正在测试的状态机:

transition_from(:offered).to(:wait_for_pap_confirmation).on_event(:pap_choosed).on(:status)