문제

I've made a state machine to determine a dynamic initial state of dormant or seeking_flesh. I'm receiving the following error after running RSpec:

Failure/Error: @titan = Titan.new('Abnormal', 8, false)
IndexError:
  :dormant is an invalid name

What exactly is causing this error and how can I resolve this?

spec:

describe '#state' do
  before do
    @titan = Titan.new('Abnormal', 8, false)
  end

  it 'should be dormant' do
    expect(@titan.state).to eq('dormant')
  end
end

production:

require 'state_machine'

class Titan
  def initialize(type, meters, active)
    @type = type
    @meters = meters
    @active = active
    super()
  end

  state_machine :state, initial: ->(titan) { titan.active? ? :seeking_flesh : :dormant } do
    # just enough to pass...
  end

  def active?
    current_hour = Time.now.hour
    if current_hour <= 19 && current_hour >= 5
      @time = true
    end
  end
end
도움이 되었습니까?

해결책

When declaring a dynamic state, all of the states have to be declared. This also allows you to start thinking of any other states the Titan, or your object might get involved in. Also, if you're using rubocop this follows the new 1.9 lambda syntax for anyone who got stuck with that.

Solution:

state_machine :state, initial: ->(t) { t.active? ? :seeking_flesh : :dormant } do
  state :dormant, :seeking_flesh, :attacking # this must be present
end
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top