Reputation: 99
I'm learning tests with PHP, i need to test a function that returns a view and i still can't find a way to do this. For example the function bellow:
public function getEmails(){
if (Defender::hasPermission("users")) {
$index = $this->diretorioPrincipal;
$route = $this->nameView;
return view("{$this->index}.{$this->nameView}.emails", compact('index', 'route'));
} else {
return redirect("/{$this->index}");
}
}
Can somebody plase explain how to test this function?
Upvotes: 1
Views: 2182
Reputation: 2709
You will need to create a test with php artisan make:test <TestName>
. Afterwards in your test you will typically call the setup method for initializing general values. (maybe a user or a model)
I dont know the route to your method so lets assume it is route('myMethod')
, You will also have to use 2 diffrent users: $user1
and $user2
one should have the permission users
and one should not have it so that both cases are tested.
class SomeControllerTest extends TestCase
{
/**
* Setup stuff
**/
public function setUp(): void
{
parent::setUp();
}
//All tests must be written as test<SomeName>
public function testMyFunction()
{
//user1 does have the permission
$response = $this->actingAs($user1)->get(route('myFunction'));
//the view response has code status 200 so we will check if the response is ok = 200
$resp->assertOk();
//user2 does not have the permission
$response = $this->actingAs($user2)->get(route('myFunction'));
//the redirect response is has status code 302 so we will check if the response is a redirect = 302
$resp->assertRedirect();
}
}
This is some basic approach, but I tried to incorporate your method. If anything is unclear just keep on asking.
Upvotes: 2