Maybe because you again create rows in database ...
Jul 1, 2016
10
Level 9
Test not working together
Hi, the second test below is only successful when it run separately. Why is this?
<?php
use Laracasts\TestDummy\Factory;
use Laracasts\TestDummy\DbTestCase;
class OrganisationObserverTest extends DbTestCase {
/** @test */
public function it_deactivates_custom_questions_on_organisation_deactivation()
{
$organisation = Factory::create('App\Models\Organisation');
$location = Factory::create('App\Models\Location',[
'organisation_id' => $organisation->id
]);
$location2 = Factory::create('App\Models\Location',[
'organisation_id' => $organisation->id
]);
$question = Factory::create('App\Models\Question');
$question2 = Factory::create('App\Models\Question');
$organisation->locations()->saveMany([$location,$location2]);
$location->questions()->attach($question->id);
$location2->questions()->attach($question2->id);
$organisation->active = false;
$organisation->save();
$this->assertFalse($question->fresh()->active);
$this->assertFalse($question2->fresh()->active);
}
/** @test */
public function it_activates_custom_questions_on_organisation_activation()
{
$organisation = Factory::create('App\Models\Organisation',[
'active' => false
]);
$location = Factory::create('App\Models\Location',[
'organisation_id' => $organisation->id
]);
$location2 = Factory::create('App\Models\Location',[
'organisation_id' => $organisation->id
]);
$question = Factory::create('App\Models\Question',[
'active' => false
]);
$question2 = Factory::create('App\Models\Question',[
'active' => false
]);
$organisation->locations()->saveMany([$location,$location2]);
$location->questions()->attach($question->id);
$location2->questions()->attach($question2->id);
$organisation->active = true;
$organisation->save();
$this->assertTrue($question->fresh()->active);
$this->assertTrue($question2->fresh()->active);
}
}
<?php
namespace App\Models\Observers;
class OrganisationObserver {
public function updating($organisation)
{
$current = $organisation->active;
$previous = $organisation->getOriginal()['active'];
$hasDeactivated = $current === false && $previous === true;
$hasActivated = $current === true && $previous === false;
if($hasDeactivated){
$this->setQuestionActive($organisation,false);
}
if($hasActivated){
$this->setQuestionActive($organisation,true);
}
}
private function setQuestionActive($organisation,$isActive){
$organisation->load(['locations.questions' => function ($q) use ( &$questions,$isActive ) {
$questions = $q->where('default','=','false')->update(['active' => $isActive]);
}]);
}
}
Please or to participate in this conversation.