Skip to content
This repository has been archived by the owner on May 11, 2022. It is now read-only.

state_machine callback not triggered in spec when using ActiveRecord::Observer.with_observers #27

Open
cscairns opened this issue Aug 6, 2012 · 3 comments

Comments

@cscairns
Copy link

cscairns commented Aug 6, 2012

I'm using the state_machine gem in conjunction with no-peeping-toms. In the spec that I have written at the bottom, the state_machine callback after_game_ended is never called. I verified that it is called through the development console and places in my environment.

# models/event.rb
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
  end
end

# observers/event_observer.rb
class EventObserver < ActiveRecord::Observer

  def after_game_ended(record, transition)
    # never reaches here
    ResolveGamesWorker.perform(record.id)
  end

end

# spec/models/event_spec.rb
describe Event do

  context 'when game ends' do
    subject { FactoryGirl.build(:event, :in_progress) }

    it 'should queue up event for games resolution worker' do
      ActiveRecord::Observer.with_observers(:event_observer) do
        ResolveGamesWorker.any_instance.should_receive(:perform)
        subject.game_ended!
      end
    end
  end

end
@patmaddox
Copy link
Owner

When you say "it never reaches here" are you saying that because the test fails? If so I think the test is set up incorrectly, or at least it shouldn't pass with this code. ResolveGamesWorker.any_instance.should_receive(:perform) sets an expectation for #perform to be called on an instance of ResolveGamesWorker while after_game_ended calls ResolveGamesWorker.perform - a class method. For that expectation to bet met you'd need to change it to ResolveGamesWorker.should_receive(:perform) OR change the call to ResolveGamesWorker.new.perform(record.id). Does that help?

@cscairns
Copy link
Author

cscairns commented Aug 7, 2012

It fails because it actually never triggers the callback after_game_ended. If I try Rails.logger.info("I made it!") or puts "yea dawg" before the call to ResolveGamesWorker in the event observer, the output never makes it to test.log or the console, respectively.

I've tried other assertions besides ResolveGamesWorker.any_instance.should_receive(:perform) just to make sure that I didn't write a bad test and it always fails.

@patmaddox
Copy link
Owner

Honestly Chris I'm not sure from looking at your code, and I'm not familiar enough with state_machine's inner workings to know what might be going on. If you sort this out please send a pull request, for now I'm afraid I can't investigate further.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants