Test that the elements in a collection belongs to an user
Hi!
I'm writing a Livewire component called Habits. I would like to test that the user only see the habits that belong to him. This is the current code of the render method.
public function render()
{
return view('livewire.habit.index', [
'habits' => Habit::where('user_id', Auth::id())->paginate(10),
]);
}
I tried moving habits to a public property, but then Livewire complained about the public properties can't be a Collection. I converted the collection to an array and then the view complained about not finding the properties of the object.
Not sure what is the best strategy to accomplish this.
Thanks @tray2! I followed your advice and I have the tests working perfectly now. I implement them like this:
/** @test */
function user_can_see_habits_belong_him()
{
$currentUser = User::factory()->create();
$this->actingAs($currentUser);
$habit = Habit::factory()->createOne([
'name' => 'currrent-user-habit',
'user_id' => $currentUser->id
]);
Livewire::test(Index::class)
->assertSee($habit->name);
}
/** @test */
function user_can_not_see_habits_do_not_belong_him()
{
// Current User
$this->actingAs(User::factory()->create());
// Second user, owner of the new Habit
$secondUser = User::factory()->create();
$habit = Habit::factory()->createOne([
'name' => 'second-user-habit',
'user_id' => $secondUser->id
]);
Livewire::test(Index::class)
->assertDontSee($habit->name);
}
I wasn't sure of using some text to verify if the functionality was working correctly or not, because text can change more often, but like I'm controlling the text directly from the test, I think is good enough.