lara16177's avatar

Should I avoid using Laravel helpers in tests

I see a some tutorials avoiding the use of helpers in their tests and others that seem to make use of them.

Part of the creation process for a model is that a slug is created from its name. This is done using the Str::slug('...'); helper.

Now when testing that a model has been created successfully, and that the slug has been created correctly based on the name of the model, is it 'acceptable' to use the Str::slug() helper in my test or is there any reason I should be manually constructing the slug?

$this->assertEqual(Str::slug('abc xyz'), Model::find(1)->slug);

$this->assertEqual('abc-xyz', Model::find(1)->slug);
0 likes
1 reply
martinbean's avatar
Level 80

@veleous You shouldn’t be duplicating any business logic in tests (which is what you’re doing here) regardless where it uses helpers or not. If you copy the logic of how you generate slugs in your test, but then change it in your application code, you’re test is now out of sync.

Instead, test with known values if you want to test how your slugs are generated:

$this->post('/posts', [
    'title' => 'A Test Post Title',
]);

// Now check post was created in database with slug value you are expecting...
$this->assertDatabaseHas('posts', [
    'title' => 'A Test Post Title',
    'slug' => 'a-test-post-title',
]);

You’re no longer duplicating your slug generation logic to your test and instead just asserting the result.

1 like

Please or to participate in this conversation.