Today, we're diving into a discussion on testing complex queries inside a Laravel controller. Testing these methods directly within a Feature test can quickly become overwhelming and hard to manage.
app->instance(UserRepository::class, $userRepository); $results = factory(User::class, 3)->create(); $userRepository->shouldReceive('searchAndFilter') ->once() ->andReturn($results); $response = $this->get('/users/search'); $response->assertStatus(200); $response->assertViewIs('users.search_results'); $response->assertViewHas('results', $results); } // other test without mocking the user repository class }
use App\Models\User; use Tests\TestCase; class UserTest extends TestCase { public function test_search() { } public function test_only_editor() { } public function test_filter_by_status() { }}
Not everyone in the Laravel community is a big fan of using the repository pattern or mocking Laravel models.