Browse AI Field GuideForum Podcast
All ThreadsLeaderboard
  1. Discussions

    1. Popular This Week
    2. Popular All Time
    3. Solved
    4. Unsolved
    5. No Replies Yet

DennisEilander's avatar

Unit test shows response body in console

Hi, I'm trying to write a test to check if a non-existing urlKey is redirecting to the global redirect url. But when I run the phpunit in my console, the output contains the redirect body of the $response For example: mywebsite.com/non-existing-url must redirect to a global domain, which is set in the config file This is my test: /** @test */ public function it_will_redirect_to

DennisEilander's avatar
DennisEilander's avatar DennisEila...6yrs agoLaravel
4
1
Last reply by DennisEilander 6yrs ago
kkhicher1's avatar

Test Single Pass but Fail when i test All

<?php namespace Tests\Unit; use App\Book; use App\User; use Tests\TestCase; use App\Reservation; use Exception; use Illuminate\Foundation\Testing\WithFaker; use Illuminate\Foundation\Testing\RefreshDatabase; class BookReservationTest extends TestCase { use RefreshDatabase; /** * @test */ public function a_book_can_be_checked_out() { // $b

kkhicher1's avatar
kkhicher1's avatar drewdan6yrs agoTesting
8
1
Last reply by drewdan 6yrs ago
BrownieCoffee's avatar

Test redirection signup to login

Hi there ! I'm doing test for signup right now and I have problem. I try to redirect user to route('login') from route('signup'). My validation request public function signup() { return view('auth.signup'); } public function signupPost(Request $request) { $requestTwo = $request->validate([ 'username' => 'required|string|min:3

BrownieCoffee's avatar
BrownieCoffee's avatar BrownieCof...6yrs agoTesting
12
2
Last reply by BrownieCoffee 6yrs ago
trip.somers's avatar

SoftDeletes + Observer = volatile test?

I have a test that occasionally throws an exception, I'd guess about 3-5% of the time. It appears to be a race condition related to Eloquent model events and an Observer. I do not understand how there is a race condition. Below, I have included my test and the related Observer. public function testRestore() { $deleteResource = factory(Engagement::class)->crea

trip.somers's avatar
trip.somers's avatar trip.somer...5yrs agoTesting
3
1
Last reply by trip.somers 5yrs ago
moxir's avatar

HTTP Test

Hi, I'm trying to create tests for my application. However, when I try to test CRUD operations, the instance passed into the method is not loaded from the database. Let's say I have this method: public function destroy(Comment $comment) { $comment->delete(); return redirect()->back(); } Now, when using the application, everything is working. The c

moxir's avatar
moxir's avatar moxir6yrs agoTesting
6
1
Last reply by moxir 6yrs ago
jrdavidson's avatar

Generating Test with Mocking Query

I have the main feature request test partly written. On my users.index page it renders 3 different Livewire components that are paginated user datatables. One for active, one for inactive, and unactivated. I'm wanting to test each individual Livewire component. The problem I'm having is that I was trying to run a query inside of the test and make sure I return the right data.

jrdavidson's avatar
jrdavidson's avatar xtremer3606yrs agoTesting
9
1
Last reply by xtremer360 6yrs ago
osama_abdullah's avatar

when i test autherization in laravel nova using php unit, my policies are not getting hit

i want to write test for authorization but wen i send requests from php unit, it only hits that default gate that is predefined in novaServiceProvider. so who can i make php unit requests hit policies as expected

osama_abdullah's avatar
osama_abdullah's avatar osama_abdu...6yrs agoNova
0
1
abdulrafey38's avatar

Laravel Test Folder

Whats the purpose of Test folder in laravel does ever i need it in development purpose or its just a laravel thing.

abdulrafey38's avatar
abdulrafey38's avatar Tray26yrs agoLaravel
3
1
Last reply by Tray2 6yrs ago
m7vm7v's avatar

How to test the laravel passport api routes

I am on the latest Laravel with initial passport installation In my test i have - $userEmail = '[email protected]'; $userPassword = 'my-password'; $userApiSecretName = 'token'; $userApiSecretRedirect = 'https://test.com/callback'; $user = factory(User::class)->create([ 'email' => $userEmail, 'password' =>

m7vm7v's avatar
m7vm7v's avatar m7vm7v6yrs agoLaravel
5
1
Last reply by m7vm7v 6yrs ago
jgravois's avatar

Test results in Array (...) does not match expected type "string".

I am working on a report that shows a rolling 12-month span. I started with a test but got hit with Array (...) does not match expected type "string". /** @test */ public function can_create_a_12_month_rolling_array () { $dt = Carbon::today(); $reporter[] = [ 'name' => $dt->format('F Y') ]; for($i=1; $i<13; $i+

jgravois's avatar
jgravois's avatar bobbybouwm...6yrs agoTesting
1
1
Last reply by bobbybouwmann 6yrs ago
jesse_orange_newable's avatar

Using auth()->user() within a test

In an application I'm building a Comment can have a relation to both a User and an Article, so when creating the comment I just do the following: $article->comments()->create($request->validated()); Then to associate the User I hook into the creating event of the Comment model to associate the user with the comment like so: $comment->user()->associate(auth()-

jesse_orange_newable's avatar
jesse_orange_newable's avatar abhijeet99...6yrs agoTesting
1
1
Last reply by abhijeet9920 6yrs ago
Albertopeinado's avatar

Test fails when running phpunit globally, works when executed alone

So basically if I use the phpunit command to execute the test, I get this error: There was 1 error: Tests\Feature\ViewMoviesTest::the_main_page_shows_correct_info Error: Call to undefined function GuzzleHttp_idn_uri_convert() If I execute it in PHPStorm with the Run 'the_main_page_shows..' it passes correctly. I have no clue why this is happening, in other projects this worke

Albertopeinado's avatar
Albertopeinado's avatar bugsysha6yrs agoTesting
3
1
Last reply by bugsysha 6yrs ago
TheRealHyveMind's avatar

Laravel 7, Test Command not working

Afternoon everyone, Hope you're all doing well. I was just wondering if someone had any insight into exactly what is going wrong with my artisan command. Perhaps it's something simple I've missed and I've been at the desk too long. I've just upgraded from Laravel 6 -> Laravel 7, and I'm running through making sure everything works. Attempting to run my tests works fine as us

TheRealHyveMind's avatar
TheRealHyveMind's avatar AlecWeekes6yrs agoLaravel
2
1
Last reply by AlecWeekes 6yrs ago
materom's avatar

@dataProvider fails running Test

I have this CreditLimit test that does test an API response. This works as excpected. /** @test */ public function get_credit_limit_data() { $this->withoutExceptionHandling(); $this->withoutMiddleware(); $response = $this->get('api/customer/credit_limit/9yZV&WrLBiBxN@ZACBQVxcLCMc74fQ/10003'); $response->assertStatus(200); $response->asse

materom's avatar
materom's avatar materom6yrs agoTesting
2
1
Last reply by materom 6yrs ago
keizah7's avatar

SQLite foreign key dont set null on delete in phpunit test

Hello, I have migration where I add foreign key to threads table (https://github.com/keizah7/forum/commit/e1aa1b31555c9469091be178e23f5746c377c080#diff-873a697d9df8d6d454c40acbb165080e) Problem is that in phpunit test sqlite don't set foreign key null on delete. 1) Tests\Feature\BestReplyTest::if_a_best_reply_is_deleted_then_the_thread_is_properly_updated_to_reflect_that Failed

keizah7's avatar
keizah7's avatar amirrezam7...5yrs agoTesting
11
1
Last reply by amirrezam75 5yrs ago
Squire's avatar

Table, wasRecentlyCreated and model keys make test fail

If I create resources from my test case and then compare it from what I get in the controller it fails because: Somehow all the objects in the collection inside the test have the table attribute as null. The wasRecentlyCreated attribute is set to true while in the controller it's false. The primary key and foreign key are set to integer in the test case while in the contr

Squire's avatar
Squire's avatar mynameisco...6yrs agoTesting
7
2
Last reply by mynameiscody07 6yrs ago
LearningLaravelYai's avatar

Test: CustomRequest + Validation

I want to write a Test, that: 1: Uses a CustomRequest class, with validation rules. 2: Write a test, that only test this classs. 3: I do not want to create a controller in this case. 4: I would prefer it to be a unit test, and not a features test. app\Http\Requests\CustomRequest.php <?php namespace App\Http\Requests; use Illuminate\Foundation\Http\FormRequest; class Custo

LearningLaravelYai's avatar
LearningLaravelYai's avatar LearningLa...6yrs agoLaravel
0
1
Ranx99's avatar

How to test a job when it fails?

I want to make sure that a job will be re-tried after x minutes when it fails: class ExampleJob implements ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; public $retryAfter = 300; public function handle() { //code } } So if I have the above job, how can I test that it will be retried after 5 minutes when it fails?

Ranx99's avatar
Ranx99's avatar Ranx996yrs agoTesting
0
1
wipflash's avatar

Writing Unit test with mokery

I want to write a unit test using mockery for following example code block. protected function evaluate(): EvaluationResult { try { $smtpTransport = \App::make(\Swift_SmtpTransport::class, [ 'host' => config('mail.host'), 'port' => config('mail.port'), 'encryption' => config('mail.encryption')

wipflash's avatar
wipflash's avatar bugsysha6yrs agoTesting
3
1
Last reply by bugsysha 6yrs ago
asmerkin's avatar

How to test a Queued Closure

Hi, I'm learning to work using TDD and Laravel. Everything is going great so far, but now I have a doubt about how to test a Queued Closure is dispatched. Any clues?

asmerkin's avatar
asmerkin's avatar bobbybouwm...6yrs agoTesting
3
2
Last reply by bobbybouwmann 6yrs ago
mstdmstd's avatar

How to make cypress different test depending on if there are rows

Hello, In @vue/cli 4.0.5 app making cypress for a bloc like <fieldset class="blocks m-1 p-1"> <legend class="blocks block-wrapper-for-data-listing">Events&nbsp;</legend> <div class="table-responsive table-wrapper-for-data-listing" v-if="taskRow.events.length">

mstdmstd's avatar
mstdmstd's avatar mstdmstd6yrs agoTesting
0
1
finchy70's avatar

Test post doesn't hit endpoint

Here is my route. Route::post('/likes/{reply}', 'LikeController@store')->name('likes.store'); Here is my test /** @test */ public function an_authenticated_user_can_like_any_reply() { $this->signIn(); $reply = create(Reply::class); $this->withoutExceptionHandling()->post('likes/'.$reply->id); $this->assertCount(1, $r

finchy70's avatar
finchy70's avatar finchy706yrs agoTesting
2
1
Last reply by finchy70 6yrs ago
KalimeroMK's avatar

Test Invitation Mail

When admin create a user it sends invitation email with a password reset link and it working nice when is sending the mail manually on the staging server but need to write a test but when run the test is failing hire is my code Controller public function store(CreateUser $request) { $input = $request->validated(); if ($user = User::getByEmail($input['emai

KalimeroMK's avatar
KalimeroMK's avatar KalimeroMK6yrs agoLaravel
8
1
Last reply by KalimeroMK 6yrs ago
KeironLowe92's avatar

Better way to write this test for a Store controller method?

So I've got a system with 4 roles, Super Admin, Admin, Editor, Viewer. I'm trying to write a test for the store method of a controller that ensures that users can't create users with a higher role than their own. So Admins can't create Super Admins, Editors can't create Super Admins or Admins etc etc. I've got a working test, but I feel like it could be improved a lot but I'm n

KeironLowe92's avatar
KeironLowe92's avatar james_fair...6yrs agoTesting
1
1
Last reply by james_fairhurst 6yrs ago
socieboy's avatar

@can condition on blade is not working on test unit

Does anyone know if there is something special on the @can condition when running the test case? I have a test that assertSeeText('') inside of this directive, but when i look at the HTML the HTML inside is not being rendered, if i change the @can for a @if with the the same condition that the user have specific role it works. I will appreciate the help.

socieboy's avatar
socieboy's avatar socieboy6yrs agoTesting
1
1
Last reply by socieboy 6yrs ago
KalimeroMK's avatar

Unit test 2FA

have implemented Google 2 factor Authorization on my page and it is working but I was wondering if it possible to unit test it, if can be done, can someone tell me how to do it

KalimeroMK's avatar
KalimeroMK's avatar martinbean5yrs agoLaravel
3
1
Last reply by martinbean 5yrs ago
Ranx99's avatar

Is this considered as a unit test?

I am trying to understand the different between a unit test and a feature test: lets say I am trying to test the password reset notification: PasswordResetNotificationTest.php /** @test */ public function is_pushed_to_a_queue() { Queue::fake(); $user = factory(User::class)->create(); $user->notify(new ResetPassword('secret-token')); $this->assertEqua

Ranx99's avatar
Ranx99's avatar Tray26yrs agoTesting
1
1
Last reply by Tray2 6yrs ago
m21s's avatar

Facade error with the new Http Client in test

I just created a new Laravel 7 project. I required guzzle and added \Illuminate\Support\Facades\Http::fake(); into Tests\Unit\ExampleTest@testBasicTest. When I run the tests, I get the following: FAIL Unit\ExampleTest ✕ basic test Tests: 1 failed, 1 pending RuntimeException A facade root has not been set. at vendor/laravel/framework/src/Illuminate/Support/Fa

m21s's avatar
m21s's avatar m21s6yrs agoLaravel
4
1
Last reply by m21s 6yrs ago
siewlon6093's avatar

This test did not perform any assertions

$ vendor/bin/phpunit --filter ParticipateInFormTest PHPUnit 8.5.2 by Sebastian Bergmann and contributors. R 1 / 1 (100%) Time: 6.52 seconds, Memory: 24.00 MB There was 1 risky test: 1) Tests\Feature\ParticipateInFormTest::test_an_authenticated_user_may_participate_in_forum_threads This test did not perform an

siewlon6093's avatar
siewlon6093's avatar STEREOH6yrs agoLaravel
1
1
Last reply by STEREOH 6yrs ago
rshepard21's avatar

Need to Test for Duplicate Slugs

I am trying to create a unit test for duplicate slugs, I am using the following code to test: public function a_post_cannot_have_a_duplicate_slug() { $post = factory('App\Post')->raw(); $this->assertDatabaseMissing('posts', $post); } I cannot for my own life figure out what I need to do to check for if a slug already exists in testing. Help is ve

rshepard21's avatar
rshepard21's avatar STEREOH6yrs agoTesting
5
1
Last reply by STEREOH 6yrs ago
amoonu's avatar

How to test controller methods that require cookies

I need to test a controller method that fetches a cookie with \Cookie::get(). I have been trying for days to mock this cookie in my tests but to no avail. How do I got about this?

amoonu's avatar
amoonu's avatar Sti3bas6yrs agoTesting
4
1
Last reply by Sti3bas 6yrs ago
Ranx99's avatar

How to test routes that are protected by a middleware?

Let's say I have a group of routes which are protected by a middleware: Route::group(['middleware' => 'verified'], function () { Route::get('/profile', 'ProfileController@show')->name('profile.show'); Route::get('/settings', 'SettingsController@show')->name('settings.show'); }); How can I test that these routes are protected by verified middleware? If I writ

Ranx99's avatar
Ranx99's avatar alanholmes6yrs agoTesting
5
1
Last reply by alanholmes 6yrs ago
theblack68's avatar

How Test a Security Download

Hello ...I have create an Application with Laravel. Among other things, this application allows you to view pdf files. In order to do this, you must have special requirements. I created a path in storage/app/upload where the files to show are taken from. In the controller who takes care of recovering the right one I have in the show method this snippet: return response()->do

theblack68's avatar
theblack68's avatar theblack686yrs agoLaravel
2
1
Last reply by theblack68 6yrs ago
jrdavidson's avatar

Trying to Test a Mock of a Filters Class

I'm attempting to try and unit test the class below. I don't know if this is the proper way to do it but this is what I"m attempting. The first assertion in each test fails due to these error messages. Failed asserting that an array contains 'App\Filters\Concerns\FiltersByStatus'. Failed asserting that an array contains 'App\Filters\Concerns\FiltersByStartDate'. What sugge

jrdavidson's avatar
jrdavidson's avatar xtremer3606yrs agoTesting
4
1
Last reply by xtremer360 6yrs ago
swist's avatar

php artisan test is not available after updating to 7.0

Hi, I updated Laravel to 7.0 and everything works fine, php artisan -V returns Laravel Framework 7.0.4, new Str class works fine but there is no php artisan test command. Do you have an idea why? Here is php artisan output:

swist's avatar
swist's avatar swist6yrs agoLaravel
12
1
Last reply by swist 6yrs ago
pascual's avatar

Any working setup of mochapack + Laravel Mix + Vue Test Utils?

Hello wonderful people, I am currently studying the "Testing Vue" course here at Laracasts (https://laracasts.com/series/testing-vue). While the course is great as one can expect from anything at this site, the specific implementation details of setting up the testing environment given seems to be a bit outdated. I have played around with the dependencies a lot, to no

pascual's avatar
pascual's avatar pascual6yrs agoVue
1
1
Last reply by pascual 6yrs ago
Agoi's avatar

Assert Email was sent sends email and test fails

I have a method that creates a new user, sends welcome email and verification email like below: protected function createNewUser() { $user = $this->createUser(); Mail::to($user)->send(new Welcome($user)); Mail::to($user)->send(new ConfirmEmail($user)); $this->createProfileFor($user); $this->createUserVerification($u

Agoi's avatar
Agoi's avatar Agoi6yrs agoTesting
1
1
Last reply by Agoi 6yrs ago
Agoi's avatar

Test Wrong Password throws an Exception During Auth Test

Hi everyone, I have a code like below $user = \App\User::where('email', trim($this->email))->firstOrFail(); //compare password if (! Hash::check(trim($this->password), $user->password) ) { throw new \Illuminate\Database\Eloquent\ModelNotFoundException; } $user->update([ 'auth_token' => custom_un

Agoi's avatar
Agoi's avatar Sti3bas6yrs agoTesting
8
1
Last reply by Sti3bas 6yrs ago
FerranMunoz's avatar

Update FormRequest in Unit Test

Hello. Today I started wih the unit test in my repository pattern and everything it's ok instead one method: update the information. UserTest.php <?php use App\User; use App\Http\Controllers\UserController; use App\Http\Requests\UserRequest; use App\Repositories\UserRepository; use App\Services\UserService; use Illuminate\Support\Facades\Event; use Illuminate\Http\Request;

FerranMunoz's avatar
FerranMunoz's avatar FerranMuno...6yrs agoGeneral
2
1
Last reply by FerranMunoz 6yrs ago
jgravois's avatar

Trying to test if a relationship exists

I am trying to test if the relationship on a model exists and is empty but the test fails with Property [bands] does not exist on this collection instance. /** @test */ public function a_consignment_can_be_a_fixed_rate () { $this->withoutExceptionHandling(); $con = Consignment::with('bands')->whereConsignmentCode('FIXED')->get(); $this->

jgravois's avatar
jgravois's avatar Talinon6yrs agoTesting
1
1
Last reply by Talinon 6yrs ago
Hala's avatar

Agent feature test

I'm doing feature test when i sent Agent user with headers and dd(new agent ()->platform) i got false , i checked the route using postman and it's all looks great how can i fix this issue ? this is the test /** @test * */ public function app_version_api_return_404_for_not_exists_versions() { $version=create(AppVersion::class); $response= $this->getJson("

Hala's avatar
Hala's avatar Sti3bas6yrs agoTesting
6
1
Last reply by Sti3bas 6yrs ago
shanely's avatar

what is the difference of Unit test and Feature Test

Hi I have this version of laravel in my compose "laravel/framework": "^6.2", In test folder there are 2 folders inside test and feature folder. can I ask what is the difference of this two and what should I test for test folder and feature test folder. Thank you in advance

shanely's avatar
shanely's avatar Tray26yrs agoLaravel
7
7
Last reply by Tray2 6yrs ago
benou101's avatar

Integration Test: use URL::route or hardcode the route

When testing a controller, all the example I've seen so far hardcode the route. For example, to test if you can delete something, I see: $this->delete(''something/'.$something->id). But if the path to "something" becomes "somethingElse", you have to change all your tests. Would it be better to do: $this->delete(URL::route('something.destroy', $some

benou101's avatar
benou101's avatar Sti3bas6yrs agoTesting
2
1
Last reply by Sti3bas 6yrs ago
sirhxalot's avatar

How to Test if a verification email was queued?

Hi Folks! I would like to write a PHPUnit test where I would like to proof if the verification email was send after register. My goal is to override the email template used to send for the verification email therefore I have made the following changes: App\User public function sendEmailVerificationNotification() { $this->notify((new VerificationEMail)); }

sirhxalot's avatar
sirhxalot's avatar sirhxalot6yrs agoLaravel
21
10
Last reply by sirhxalot 6yrs ago
ArneDB's avatar

Laravel Dusk: Running one test at a time works, but when running two tests or more a PDOException is thrown

Hello there, I have a few dusk tests, they're slow high level tests, they give me alot of comfort! :D I can run every single one of these tests in isoloation with --filter, but when I just run php artisan dusk, the first test works, but after that the tests generate SQLSTATE[HY000]: General error: 10 disk I/O error There's always another SQL error, here's some examples: (SQL: a

ArneDB's avatar
ArneDB's avatar ArneDB6yrs agoTesting
2
1
Last reply by ArneDB 6yrs ago
farshadf's avatar

simple create test with logged in user in laravel 5

i want to write a test for my comment model but for making that the user must be logged in i want to know how people write create tests in laravel because when i make it with the below method : $file = UploadedFile::fake()->create('image.jpg'); $data = [ 'title' => $this->faker->word, 'link' => $this->faker->url,

farshadf's avatar
farshadf's avatar ahmeddabak6yrs agoLaravel
1
1
Last reply by ahmeddabak 6yrs ago
luisvdbl's avatar

Test similar web and api controllers

Suppose that we have a Post model and we have two separate web and api routes/controllers to create a new post /posts -> PostsController@store /api/posts -> Api/PostsController@store The web controller would be something like these <?php use App\Http\Controllers\Controller; use use App\Http\Requests\StorePost; use App\Services\CreatePostService; namespace App\Http\

luisvdbl's avatar
luisvdbl's avatar bugsysha6yrs agoTesting
1
1
Last reply by bugsysha 6yrs ago
danzar's avatar

Migration error on unit test run

When I run the unit tests i receive an error about missing migration table. I have put the use RefreshDatabase; on the unit test class. Illuminate\Database\QueryException: SQLSTATE[HY000]: General error: 1 no such table: migrations (SQL: select exists(select * from "migrations" where "migration" = 2019_12_26_131421_create_subscription_details) as "exist

danzar's avatar
danzar's avatar Hesesses2yrs agoTesting
4
1
Last reply by Hesesses 2yrs ago
Kovah's avatar

Eager loading of a model relation works in browser, but not in PHPunit test

I have a really weird issue that I am not able to solve right now. The full code is available on Github. Status Quo Currently, I have the standard user model and a settings model. A setting is bound to a user via a user_id field. The user model has a $user->rawSettings relation which eager-loads the related settings. I use eager loading here to prevent database calls for eac

Kovah's avatar
Kovah's avatar bugsysha6yrs agoLaravel
6
1
Last reply by bugsysha 6yrs ago
Janghan's avatar

PHPunit test sometimes fails....

I have no idea why the result of the test can be changed..... Is there anyone who knows that problem and some assumable reasons???

Janghan's avatar
Janghan's avatar Janghan6yrs agoTesting
3
1
Last reply by Janghan 6yrs ago

Want us to email you occasionally with Laracasts news?

Nine out of ten doctors recommend Laracasts over competing brands. Come inside, see for yourself, and massively level up your development skills in the process.

Learn
BrowseSeriesCreatorSeriesLaravel PathLarabitsPlayground
Discuss
ForumPodcastSupport
Extras
Gift CertificatesApparelFAQiOS AppTerms
Social
X(Twitter)TikTokYoutube

© Laracasts 2026. All rights reserved. Yes, all of them. That means you, Todd.

Proudly hosted with Laravel Forge and DigitalOcean.

Want us to email you occasionally with Laracasts news?

Nine out of ten doctors recommend Laracasts over competing brands. Come inside, see for yourself, and massively level up your development skills in the process.

Learn
BrowseSeriesCreatorSeriesLaravel PathLarabitsPlayground
Discuss
ForumPodcastSupport
Extras
Gift CertificatesApparelFAQiOS AppTerms
Social
X(Twitter)TikTokYoutube

© Laracasts 2026. All rights reserved. Yes, all of them. That means you, Todd.

Proudly hosted with Laravel Forge and DigitalOcean.