I could use some help writing a feature test for a route that returns streamed content. Here’s the details…
I have a Laravel route:
Route::get('/export/user/role/{role}', [AdminExportUserController::class, 'export'])->name('export.user');
that will call the export controller method below. The export() method gets a collection of users from the database and streams rows of users in ‘.csv’ format to the browser.
Here’s the export method:
<?php
namespace AppHttpControllersAdmin;
use AppModelsUser;
use AppEnumsRoleEnum;
use AppHttpControllersController;
use SpatieSimpleExcelSimpleExcelWriter;
class ExportUserController extends Controller
{
public function export(RoleEnum $role)
{
$filename = strtolower($role->value) . '.csv';
$filetype = 'csv';
$writer = SimpleExcelWriter::streamDownload($filename, $filetype);
// First row is column labels.
$writer->addHeader([
'Company Name',
'Account Code',
'First Name',
'Last Name',
'Email',
'Registration',
'Email Verified',
'Last Login',
'Status',
'Role'
]);
User::where('role', '=', $role->value)
->orderby('first_name', 'asc')
->orderby('last_name', 'asc')
->chunk(
200, // Chunk size is arbitrary, but reasonable.
function($users) use ($writer) {
foreach($users as $user) {
$writer->addRow(
[
$user->company_name,
$user->account_code,
$user->first_name,
$user->last_name,
$user->email,
$user->local_created_at_date,
$user->local_email_verified_at_date,
$user->local_last_login_at_date,
$user->status->value,
$user->role->value,
]
);
}
flush(); // Flush the buffer every chunk.
}
);
$writer->toBrowser();
$writer->close();
}
}
I could use some help with writing a feature test for this route. I’m not sure what to test or how exactly to write it up. When I run the below test method, the streamed content to the browser is output to the terminal, mixed in with the artisan test output. I’m not sure if I should be capturing the streamed output and inspecting the content, etc..
Any tips on writing this test method and preventing the output to the terminal?
Thanks!
<?php
namespace TestsFeatureAdmin;
use AppModelsUser;
use AppEnumsRoleEnum;
use IlluminateFoundationTestingRefreshDatabase;
use TestsTestCase;
/**
* Test the 'Export Users' Feature.
*/
class UserExportTest extends TestCase
{
use RefreshDatabase;
public function test_export_users(): void
{
// Create the admin performing the activity.
$admin = User::factory()->admin()->create();
// Populate the database with users.
User::factory(4)->user()->create();
// What is the correct way to write a test for streamed content?
$response = $this
->actingAs($admin)
->get(route('admin.export.user', ['role' => RoleEnum::User->value]));
// ...?
}
}
I’ve read through the Laravel.com documentation and Googled the heck out of this, to no avail. I’m not sure where to turn. I appreciate any help.
dfaltermier is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.