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

secmuhammed's avatar

How to test Laravel api resource

How can I test the api resource without hitting the database ? , I tried to do the following, but it throws an error. $user = new User([ 'username' => 'Jonh', 'email' => '[email protected]', 'password' => bcrypt('secret'), 'created_at' => Carbon::now(), 'updated_at' => Carbon::now(), ]);

secmuhammed's avatar
secmuhammed's avatar ehab.abosh...4yrs agoTesting
2
1
Last reply by ehab.aboshehab 4yrs ago
marufalom's avatar

Reset / Turn off phpunit test coverage in PhpStrom

I have a noob question, How can I disable the line highlighting after running a test with coverage?

marufalom's avatar
marufalom's avatar Martenvanu...7yrs agoTesting
9
1
Last reply by Martenvanurk 7yrs ago
jmariller's avatar

Issue with Vue Test Utils in Laravel

Hi all, i am trying to use the Vue Test Utils libraries for testing some Vue.JS components but I am facing issues when running the tests - following error message is showing up after I run "npm test": Error: Chunk.parents: Use ChunkGroup.getParents() instead I have tried to follow the instructions from Episode 6 of the series "Testing Vue" on a fresh instal

jmariller's avatar
jmariller's avatar andreich19...6yrs agoTesting
8
1
Last reply by andreich1980 6yrs ago
matttonks11's avatar

Single test making multiple assertions

Hi, I'm not sure if I'm missing something but whenever I run one or two tests in my test suite they seem to be making multiple assertions despite the test only having one assertion. Here's an example to illustrate the point. When I include this test I get the output OK (12 tests, 21 assertions) If I comment it out however, my output is OK (11 tests, 19 assertions) /** @test */

matttonks11's avatar
matttonks11's avatar matttonks1...7yrs agoTesting
2
1
Last reply by matttonks11 7yrs ago
longestdrive's avatar

Test Mail and number of emails send

Hi My Laravel 5.5 testing journey continues How do I test how many emails were sent by my test. I'm trying to test that multiple emails were sent in a test. The method I'm testing against is only sending to the first recipient so I need to find a way of building a test My current test is this: public function testUserCanSendBroadcastMessageToMultiplePlayers() { $th

longestdrive's avatar
longestdrive's avatar longestdri...7yrs agoTesting
4
1
Last reply by longestdrive 7yrs ago
ArneDB's avatar

I don't fully understand how to test forms, type etc doesn't seem to be working

Hello there, I'm trying to write some tests for some forms on my application, but I run into the problem that I can't really access any input fields. First I tried Laravel Dusk but this is way to slow, each time I run "php artisan dusk" it takes like 10-20 seconds to boot up the chromium and run the test. Also, I run into the same issues with dusk as I do with Browser

ArneDB's avatar
ArneDB's avatar ArneDB7yrs agoGeneral
1
1
Last reply by ArneDB 7yrs ago
bwrigley's avatar

Feature Test to replicated Delete method in Route Model Binding

Hello, I'm trying to write feature tests around a new controller which uses the route model binding. But I'm having trouble replicating the DELETE method. so my routes look like this: Route::group(['middleware' => 'admin', 'prefix' => 'admin', 'as' => 'admin.'], function () { Route::get('/', 'AdminController@dashboard')->name('dashboard'); Route::resourc

bwrigley's avatar
bwrigley's avatar bwrigley7yrs agoTesting
2
1
Last reply by bwrigley 7yrs ago
jonassiewertsen's avatar

Unit Test for Morph many to many

Hej I am looking for an elegant way for a Unit test. my database is looking like: categories - id - name desks - id - name - something else categoryable - categorie_id - categoryable_id - categoryable_type The morph relations itself are working. Now im pulling some arrays from the collections to test via assertEquals, which seems like a really ugly way of doing it. $this-&g

jonassiewertsen's avatar
jonassiewertsen's avatar jonassiewe...7yrs agoTesting
2
1
Last reply by jonassiewertsen 7yrs ago
bwrigley's avatar

Feature test always gets 'session expired' message

Just starting out with feature testing so starting with basic login test that looks like this //use custom traits to create a user and activate with Sentinel $email = $this->safeEmail('example.com'); $this->createAuthenticatedUser($email, "secret"); $credentials = [ 'email' => $email, 'password' =>

bwrigley's avatar
bwrigley's avatar bwrigley7yrs agoTesting
13
1
Last reply by bwrigley 7yrs ago
successdav's avatar

Offset timestamps in unit test

Hi! I am writing a test to give the user ability sort courses from oldest to newest and I need to offset the time stamp so I can simulate a course that was create few hours ago and a course that is recently created. Thanks for your help

successdav's avatar
successdav's avatar successdav7yrs agoTesting
2
1
Last reply by successdav 7yrs ago
josuerhg's avatar

Creating a personality test with Laravel

Hey there! Two months ago I discovered Laravel and I'm absolutely loving it. I already did some very simple projects to practice, but now I would like to go try something a little bit different, that doesn't only involve the good old CRUD operations. I'm thinking about making a personality test (MBTI, especifically) using Laravel. For those who aren't familiar with MBTI (or the

josuerhg's avatar
josuerhg's avatar josuerhg7yrs agoLaravel
2
1
Last reply by josuerhg 7yrs ago
pn51291's avatar

Feature test return unexpected value

Hi guys, I'm learning about testing in Laravel with PHPUNIT. Currently, I'm testing "user login with correct credential". I expect it will redirect to a user dashboard, but PHPUNIT keep redirect to hompage. I also test it in browser, and it redirect to the page I want. Only PHPUNIT redirect to the wrong path. Thanks in advance :)

pn51291's avatar
pn51291's avatar realrandya...7yrs agoLaravel
14
1
Last reply by realrandyallen 7yrs ago
jrdavidson's avatar

Not Seeding Test Database

I'm trying to figure out why when I run make command it doesn't seed my testing database because when my test gets to the method I"m testing it says there are no roles in the database. <?php namespace Tests; use Illuminate\Foundation\Testing\DatabaseTransactions; class IntegrationTestCase extends TestCase { use DatabaseTransactions; } Makefile build: php art

jrdavidson's avatar
jrdavidson's avatar Tray27yrs agoTesting
4
1
Last reply by Tray2 7yrs ago
regal2157's avatar

Console test failing to test in order?

I'm running through https://laracasts.com/series/whats-new-in-laravel-5-7/episodes/3 and my testing results don't line up... It appears the assertDatabaseHas assertion takes priority over expectsQuestion. tests/Feature/Console/MakeUserCommandTest.php function it_generates_a_new_user() { $this->artisan('make:user') ->expectsQuestion('What name shoul

regal2157's avatar
regal2157's avatar regal21577yrs agoTesting
0
1
dynait's avatar

Test Dependencies

Hello guys, I am working on Laravel 5.7 and i'd like to ask you a question regarding the PHPUnit testing. I have a test class, let's say ProductControllerTest, with two methods testProductSoftDelete() and testProductPermanentlyDelete(). I want to use the annotation @depends in the testProductPermanentlyDelete() in order to soft-delete first a product and then get the product i

dynait's avatar
dynait's avatar dynait7yrs agoTesting
7
3
Last reply by dynait 7yrs ago
AlexWinder's avatar

How to test NewSubcription without hitting Stripe API?

Hi guys, I'm currently working on a project which I'm setting up tests on, however I've hit a wall and I'm struggling to find out how to fix this. So, I have a part of my code which when a user creates a new item on the system it requires them to subscribe using Stripe payment. This is working fine. However, I have been setting up tests whilst building up this project, but now

AlexWinder's avatar
AlexWinder's avatar AlexWinder7yrs agoTesting
0
1
biniyam20's avatar

Downloaded telescope and now my migrations to my test database won't work

Hi I downloaded telescope and followed the instructions to the t on a seperate branch. Then I had to make a hot fix on my prod branch so I checked out copy of my prod branch to expose and make the fix via a test. However to run the test, I need to migrate my db structure to my test database and when I try I keep getting this error Illuminate\Database\QueryException : SQLSTA

biniyam20's avatar
biniyam20's avatar pmatseykan...7yrs agoLaravel
2
1
Last reply by pmatseykanets 7yrs ago
mlazuardy's avatar

Laravel HTTP Test trying to get property "object" of undefined

I'm Using HTTP Test with PHPUnit to create test with users feature but when i run mySampleTest like this; $this->get(route('users.index'))->assertStatus(200); while the method of index like this $users = User::paginate(15); return view('users.index',compact('users')); and the view : <tbody> @foreach ($users->where('id', '!=' ,auth()->

mlazuardy's avatar
mlazuardy's avatar mlazuardy7yrs agoLaravel
3
2
Last reply by mlazuardy 7yrs ago
gianlupu's avatar

Problem with HTTP headers in test

Hi guys, I'm facing a problem with some application tests. I'm using Laravel 5.7. I have a test like this one $response = $this->withHeaders([ 'X-App-Version' => 2, 'X-App-Token' => '<token>', ])->json('POST', '/api/register', [ <params> ]); $response->assertStatus(200) ->assertJsonFragment([ 'status_code' => 0, ]);

gianlupu's avatar
gianlupu's avatar D97059967yrs agoTesting
1
1
Last reply by D9705996 7yrs ago
goatshark's avatar

I Forget Test Methods

Greetings, I wrote an artisan command to compensate for my constantly losing sight of what test methods I've already written for a project. While I am certain this is wheel already exists, I couldn't find it in all the other wheels. ....I'm not even sure which wheel yard to look in actually. Maybe someone can tell me which wheel I reinvented. Btw, this should work, on it's own

goatshark's avatar
goatshark's avatar goatshark7yrs agoTesting
2
2
Last reply by goatshark 7yrs ago
abeer's avatar

Test controller CRUD actions.

Hi all. I seek for a tutorial to learn how to test my CRUD actions which I created in my post controller. I can't found a good tutorial I could understand. Any help please?

abeer's avatar
abeer's avatar D97059967yrs agoTesting
1
1
Last reply by D9705996 7yrs ago
Norbertho's avatar

How to exclude users from collection where email address end .test

Hi, I have users table and it contains registered users and also users registered by me. Users registered by me have email address like this: [email protected] I would like to send email to all users in my database except users registered by me so i would like to exclude users with email addresses ending test. Is there any solution to get all the users from database except wit

Norbertho's avatar
Norbertho's avatar Norbertho7yrs agoLaravel
2
1
Last reply by Norbertho 7yrs ago
alihoushyaripour's avatar

How to write test case for all routes?

Hi, I have a project that wrote all route as RESTful api, with more than 100 routes, and now I want to write test modules for all of them and test everyone of them with differents test case. I used laravel 5.6 How can I do it? is there any simple way?

alihoushyaripour's avatar
alihoushyaripour's avatar Cronix7yrs agoLaravel
2
1
Last reply by Cronix 7yrs ago
Corben's avatar

How to test piping email to Laravel app?

My App is receiving emails, and I can import them with an artisan command. Inspired by this using the php-mime-mail-parser. Unfortunately I had no idea how to create a test for this, so I couldn't start with a TDD approach, and I wrote the implementation first. But now I'd like to have an automated test for this. How would I set this up? How can I create an email or .eml-file (

Corben's avatar
Corben's avatar Corben7yrs agoLaravel
1
1
Last reply by Corben 7yrs ago
mikail10000000's avatar

Validation auth and functional test in one method?

Hi, I'm trying to figure out the right way of testing, currently when I test things I do it in the following test, I would write a method testPostCanBeCreated() and in that method I would test if the post can be created $this->ajax('post','post',['title'=>'some text']) , plus if the post can be created with the right permissions ->assertStatus(403) and if the post can

mikail10000000's avatar
mikail10000000's avatar abbytaylor7yrs agoTesting
3
1
Last reply by abbytaylor 7yrs ago
olimorris's avatar

How to test cookies in Laravel

I'm working on a custom blog site which will have posts that users can like. I ideally wish to limit users to 1 like per post and plan on enforcing this through the setting of a cookie. Using TDD, I have the following test: /** @test */ public function a_person_can_only_like_a_post_once() { $this->withoutExceptionHandling(); $this->expectException

olimorris's avatar
olimorris's avatar ljpurcell3yrs agoTesting
2
1
Last reply by ljpurcell 3yrs ago
joshuafranks's avatar

[Dusk] Test passes when ran individually but fails when ran as part of a suite.

I've got two tests that, when ran individually, pass. If I run the entire dusk test suite, I get a failure on my second test: Error: ReflectionException: Class env does not exist /home/vagrant/code/portfoliyo/vendor/laravel/framework/src/Illuminate/Container/Container.php:779 /home/vagrant/code/portfoliyo/vendor/laravel/framework/src/Illuminate/Container/Container.php:658 /hom

joshuafranks's avatar
joshuafranks's avatar staudenmei...7yrs agoTesting
1
1
Last reply by staudenmeir 7yrs ago
alchermd's avatar

How do I test login throttling?

Hello! I've built a customized authentication system that isn't that much different from what the make:auth scaffolds for us, and have recently added throttling via the ThrottlesLogins trait. I have confirmed with manual usage that it does indeed throttle the login attempts, but have yet to find a way to write a concise test for it. What I currently have: /** @test */ public fu

alchermd's avatar
alchermd's avatar agm19846yrs agoTesting
13
3
Last reply by agm1984 6yrs ago
vdnnlrjz's avatar

This is a test

This is a test This is a test This is a test

vdnnlrjz's avatar
vdnnlrjz's avatar bobbybouwm...7yrs agoGeneral
1
1
Last reply by bobbybouwmann 7yrs ago
naknode's avatar

Test a markdown Mailable method

How would a unit test this Laravel method? I have a Mailable class called ComfirmYourEmail and this method is untested. How do I test it? Cannot seem to find answer in docs. /** * Build the message. * * @return $this */ public function build() { return $this->markdown('mail.confirm-email'); } }

naknode's avatar
naknode's avatar naknode7yrs agoTesting
4
1
Last reply by naknode 7yrs ago
Sareneathenodny's avatar

Dusk unexpectedly accessing two databases in same test

My dusk test is accessing two different databases. I'd like it to only access one. Any help would be appreciated! Details: I have two databases: one for testing (test_db) and one for production (prod_db). My .env file specifies DB_DATABASE=prod_db. My .env.dusk.local file specifies DB_DATABASE=test_db. I call php artisan dusk --env=dusk.local for this test. When my test calls f

Sareneathenodny's avatar
Sareneathenodny's avatar shez19837yrs agoTesting
5
2
Last reply by shez1983 7yrs ago
megaman7's avatar

Database testing - mocking vs test db

When testing anything which interfaces with things outside of the scope of your test (APIs, databases, file-systems, queues ect) you have a choice of mocking the thing you dont want to test or using a test version of it. Which you should use differs in each case My opinion is this. Mocking is usually easier and thus should be your first choice. However if the thing being mocked

megaman7's avatar
megaman7's avatar emiliosa5yrs agoTesting
2
1
Last reply by emiliosa 5yrs ago
GimmeMylanta's avatar

Returning a generated token in a test

Hey Guys, Im trying to write a test to check if a user gets successfully logged into our system For some reason, its not seeing the token generated by the login endpoint. I want to assert 3 things in my test. That the success flag is true .. This is currently working The message is set .. This is currently working The token gets returned .. This is the bit that i cant seem to

GimmeMylanta's avatar
GimmeMylanta's avatar Chris19817yrs agoLaravel
17
2
Last reply by Chris1981 7yrs ago
morteza's avatar

How to unit test eloquent scopes?

I want to unit test to see if specific scope will be called if i call repository method but i don't know how can i do this. Let say i have a Mobile model: namespace App; use Illuminate\Database\Eloquent\Model; class Mobile extends Model { protected $casts = [ 'verified_at' => 'datetime', ]; public function user() { return $this->belongsT

morteza's avatar
morteza's avatar Sergiu177yrs agoEloquent
4
1
Last reply by Sergiu17 7yrs ago
HardDrive's avatar

Create just one related model for feature test

If I am writing a test that contains both a user model and a post model each has an associated Model Factory. I know I can do the following to create a collection of related records but how do I create just one of each for use during a feature test. $users = factory(App\User::class, 3) ->create() ->each(function ($u) { $u->posts(

HardDrive's avatar
HardDrive's avatar RossUK7yrs agoTesting
3
1
Last reply by RossUK 7yrs ago
alchermd's avatar

If you write a test for an Eloquent model that contains business logic, is it still a Feature or a Unit test?

Hola! As an example, this Laracasts episode features a Team class that can add/remove members. The gist of the class is as follows: class Team extends Model { public function add(User $user) : void; public function remove(User $user) : void; public function count() : int; // etc... } The tests are as follows: class TeamTest extends TestCase { public functio

alchermd's avatar
alchermd's avatar lostdreame...7yrs agoTesting
1
1
Last reply by lostdreamer_nl 7yrs ago
HardDrive's avatar

Struggling to find error in test

Hi I am getting an error 500 on a test I am running and am struggling to find what I have dome wrong. Below is my test and controller method and route :) /** @test */ public function authenticated_users_can_update_existing_customer() { $this->withExceptionHandling(); $customer = factory('App\Customer')->create(); $data = [ 'compa

HardDrive's avatar
HardDrive's avatar RossUK7yrs agoTesting
5
1
Last reply by RossUK 7yrs ago
HardDrive's avatar

Localised Faker in Test - Laravel 5.5

Please can someone help me to use an en_GB instance of faker within tests. I have tried reading the docs but can only find examples of using Faker in Factories and not using WithFaker in a test like below. Here is an example of where I would like to implement it :) <?php namespace Tests\Unit; use App\User; use Tests\TestCase; use Illuminate\Foundation\Testing\WithFaker;

HardDrive's avatar
HardDrive's avatar RossUK7yrs agoTesting
1
1
Last reply by RossUK 7yrs ago
Roni's avatar

Add a macro to arrays for test assertions

Hey, just a quick question on array assertions. Does anyone know if I can wrap a test in a method/macro that runs on an array? Right now, I'm using assertTrue(in_array($needs, $responseArray)), but I'd much rather macro it and add something like $responseArray->assertContains($data) and $responseArray->assertDoesNotContain($data); Is there a way to accomplish that? Using

Roni's avatar
Roni's avatar staudenmei...7yrs agoTesting
1
1
Last reply by staudenmeir 7yrs ago
elo's avatar

Laravel PHPUnit Test Forbidden Error

I have written two PHPUnit test that updates and deletes a book record only if the user is authenticated. I am using Passport for authentication but my test fails with a 403 error for both test. What could be wrong with my code below public function test_onlyAuthenticatedUserCanUpdateBookSuccessfully() { $user = factory(User::class)->create(); Passport::a

elo's avatar
elo's avatar elo7yrs agoLaravel
2
1
Last reply by elo 7yrs ago
rawilk's avatar

Test Laravel console command from package

I developed my own version of a package and it has console commands that I need to test. All the tests run fine except for the ones that assert an output from artisan. For some reason, Artisan::output() returns "" when running the tests. Could it be that I don't have an application instance in the tests like a normal Laravel app that extends Illuminate\Foundation\Test

rawilk's avatar
rawilk's avatar wilk_randa...7yrs agoLaravel
4
1
Last reply by wilk_randall 7yrs ago
joshuajazleung's avatar

Do you create a test for each validation rule of each fields?

I was watching this video https://laracasts.com/series/phpunit-testing-in-laravel/episodes/17?autoplay=true And jeffrey creates single test for each validation rule. I am wondering if that's the standard way of testing validation rules? Say I have 10 fields and each field has 3 validation rules, that's 30 tests.... Would it be better if I create a test for each field? So only 1

joshuajazleung's avatar
joshuajazleung's avatar Tray27yrs agoTesting
3
1
Last reply by Tray2 7yrs ago
mkdesign82's avatar

Test A user Login from multi perspective

Hi I don't know if I'm doing this right or not, I'll randomly test a user login to see if the particular page works fine after the user gets login. Is this way is the right way? because I'm testing a specific page on each user login. some users survive that page others are not and at last face Laravel error page. am I doing it right?

mkdesign82's avatar
mkdesign82's avatar wilk_randa...7yrs agoTesting
1
1
Last reply by wilk_randall 7yrs ago
Roni's avatar

Test if a view partial is loaded in a phpunit test

Is there a way to access a segment of a View response object? I'm trying to test if a view partial has been loaded in a less brittle way than just using see. when I dd the response object I can find the view list #finder: Illuminate\View\FileViewFinder {#120 #files: Illuminate\Filesystem\Filesystem {#121} #paths: array:1 [ 0 => "/Users/r

Roni's avatar
Roni's avatar click7yrs agoTesting
10
1
Last reply by click 7yrs ago
Max13's avatar

Create a test DB during testing (no migration)

Hi, I'm testing a repository I'm writing, and I'd like to create a test DB (in memory) to make some tests. Basically, I would like to create a Schema which would be migrated in my test constructor, for instance: Schema::create('empty_test_models', function (Blueprint $table) { $table->increments('id'); $table->string('name'); $table->timestamps(

Max13's avatar
Max13's avatar bobbybouwm...7yrs agoTesting
9
1
Last reply by bobbybouwmann 7yrs ago
gea's avatar

How to make browser test to delete

I'm making a browser test in Laravel for testing delete. How to delete according to the id we want? My test function like this : public function testDelete() { $this->browse(function (Browser $browser) { $browser ->maximize() ->visit(new Login()) ->clickLink('Login') ->type('t

gea's avatar
gea's avatar gea7yrs agoLaravel
0
1
bigweld86's avatar

Database tables deleted after running phpunit test

Hi. Every time I run a test all my database tables (except for the migrations table) are being deleted and I have to run the migrations again. For instance, if I have the following tables: migrations users tableA tableB after running: phpunit --filter user_can_view_a_record ViewRecordTest tests/Feature/ViewRecordTest.php my tables are deleted and I end up with just the migratio

bigweld86's avatar
bigweld86's avatar kreierson5yrs agoTesting
9
2
Last reply by kreierson 5yrs ago
Herchelle's avatar

PhpUnit and Laravel 5.4 how to mock Session data during a test

I'm testing a class in laravel 5.4 with phpunit that uses the session to get data. Retrieving the session data works when accessing it directly when the app is running aka "session('consumer')" returns a value, however when i try to test a function that uses the session, I get the below error: ReflectionException: Class session does not exist Can someone please shed s

Herchelle's avatar
Herchelle's avatar Herchelle7yrs agoTesting
2
1
Last reply by Herchelle 7yrs ago
squibby's avatar

How to change env variable / config in Dusk test?

I have a .env variable link to a Laravel config file which toggles certain section in my site. In Dusk testing I want to test that certain functionality is shown / hidden depending on this state. How to set the config / or update dusk .env variable on each test? I have tried Config::set() but it doesn't seem to work. Has anyone else done this before? Thanks.

squibby's avatar
squibby's avatar Bonbonzone5yrs agoTesting
13
2
Last reply by Bonbonzone 5yrs ago
anam's avatar

Is there any way to test delay() in jobs?

How to test a job with delayed dispatching? dispatch(ProcessPodcast::class) ->delay(now()->addMinutes(10)); I have tried the following but not working. $this->expectsJobs(ProcessPodcast::class);

anam's avatar
anam's avatar johnkeo7yrs agoLaravel
2
1
Last reply by johnkeo 7yrs 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.