I'm having a strange behaviour when using context.become in a PersistentActor (Not sure if the persistence has anything to do with the cause of the problem). My code is something like:
class MyActor extends PersistentActor {
import context._
// Messages
case object Start
case object Ready
case object MessageX
// Events
case object Started
def recieveRecover: Receive = { /* Not relevant, I think */}
def receiveCommand: Receive = idle
def idle: Receive = {
case Start =>
persist(Started) { _ =>
sender() ! Ready
become(ready)
}
}
def ready: Receive = {
case MessageX => doSomething()
}
}
And I have two tests in the same MyActorSpec file. The first one simply tests the 'idle' state and the second one tests the 'ready' state:
"Test A" in {
val actorRef = system.actorOf( MyActor.props(), "test-A-actor" )
actorRef ! Start
expectMsg(Ready)
}
"Test B" in {
val actorRef = system.actorOf( MyActor.props(), "test-B-actor" )
actorRef ! Start
expectMsg(Ready) /* It fails here because for some reason the actorRef
was created with its 'receiveCommand' block equal to
the 'ready' block and not equal to the 'idle' block as its suppossed to.
So it timeouts here waiting for the message which is not handled in
the 'ready' block */
actorRef ! MessageX
testSomethingAboutTheMessageX()
}
If I run both tests, the first one succeeds but the second one fails waiting for the ready message (as explained in a comment in the second test). If I run only the second test it passes. So, I'm not sure if I did something wrong when defining the actor.
UPDATE: I tried removing the persistence for the Started
event (the persist(Started)
part) as suggested and the tests worked as expected (Both actors were created in the idle
state). So, what's happenning is that the events on the first actor instance are being persisted and then the second actor instance is replaying them, and this is because the actor instances are being created with the same persistenceId
(DOH!). So, the way to make the tests independent was simply to instantiate each actor with a diferent persistenceId
.