Reputation: 390
I'm testing my api. Before calling a route I log in user to application.
Problem is that after authentication user's id is not assigned to Auth::id()
within route call.
Here is the scenario:
Test method:
public function testApiGetOrder()
{
var_dump($this->user); // first dump
Auth::login($this->user); // Can't use $this->be($this->user) here, it would not help anyway...
var_dump(Auth::id()); // second dump
$response = $this->call('GET', '/order/' . $this->order->getKey());
$this->assertResponseOk();
$this->assertJson($response->getContent());
$this->assertJsonStringEqualsJsonString($this->order->toJson(), $response->getContent());
}
OrderController's method:
public function show($id)
{
var_dump(Auth::id()); // third dump
var_dump(Auth::user()->getKey()); // fourth dump
// Calling model's logic here
}
Output of of testApiGetOrder:
First dump: object(User)
Second dump: int(1)
Third dump: NULL
Fourth dump: int(1)
Why the value of user's id is not assigned to Auth::id()
?
Upvotes: 1
Views: 2441
Reputation: 495
You are not talking about the same instance of Auth.
In your test you got an instance of Auth library where you logged in hence you get data back. When you do a call the controller has it's own instance of auth (running within Laravel framework)
Cleaner way to create your test is to use mock of Auth library. It is tested by Laravel and during a unit test you want to test the smallest piece of code.
public function testApiGetOrder()
{
Auth::shouldReceive('id')->with($this->user->getKey())
->once()->andReturn($this->user);
Auth::shouldReceive('user')->once()->andReturn($this->user);
$response = $this->call('GET', '/order/' . $this->order->getKey());
$this->assertResponseOk();
$this->assertJson($response->getContent());
$this->assertJsonStringEqualsJsonString($this->order->toJson(), $response->getContent());
}
Upvotes: 2