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

ahinkle's avatar

How to HTTP test a registered policy?

I have a registered PostPolicy: class PostPolicy { use HandlesAuthorization; /** * Determine whether the user can delete the post. * * @param \App\Models\User $user * @param \App\Models\Post $post * @return \Illuminate\Auth\Access\Response|bool */ public function delete(User $user, Post $post) { return $user->id ===

ahinkle's avatar
ahinkle's avatar lbecket3yrs agoTesting
3
1
Last reply by lbecket 3yrs ago
mstdmstd's avatar

I got “There is no active transaction” error after I added RefreshDatabase into test file

Making in laravel 9.48.0 with mysql database http tests after I added RefreshDatabase into test file use Illuminate\Foundation\Testing\RefreshDatabase; use Illuminate\Support\Facades\Artisan; use Illuminate\Foundation\Testing\Concerns\InteractsWithExceptionHandling; use Tests\TestCase; use App\Models\{Article, User}; use Illuminate\Support\Str; class ArticlesCrudTest extends

mstdmstd's avatar
mstdmstd's avatar laracoft3yrs agoTesting
7
2
Last reply by laracoft 3yrs ago
nunodonato's avatar

artisan test is broken when vendor folder is outside the project

Hi folks I've been trying to solve this issue for a long time, but no luck. In the app I'm working on, the vendor folder is outside the project folder (reasons, don't ask :). These created a couple of challenges, but everything got sorted out and is working fine now. Well, everything except artisan test, which for some reason keeps resulting in this error message Could not open

nunodonato's avatar
nunodonato's avatar Sinnbeck3yrs agoTesting
4
1
Last reply by Sinnbeck 3yrs ago
quyle's avatar

Dusk: How to test background image rendered correcly in an element?

I had an input form which allows user to upload picture. When an image is attached, its content will be put on a preview div element using inline css of background-image for user to be able to review it. But how can I test it with Dusk? I don't see any helpers or assert that make this happen.

quyle's avatar
quyle's avatar quyle3yrs agoTesting
2
1
Last reply by quyle 3yrs ago
zenith707's avatar

Feature test returning "role does not exists" with Spatie Laravel Permission

Quite simple, but not so simple. Here is the test that fails: public function test_new_users_can_register(): void { $response = $this->post('/register', [ 'first_name' => 'Test', 'last_name' => 'User', 'email' => '[email protected]', 'password' => 'password', 'password_confirmation' => 'pas

zenith707's avatar
zenith707's avatar tykus3yrs agoTesting
4
1
Last reply by tykus 3yrs ago
ignaciodev's avatar

How to test query methods from traits

I have the following trait that I want to use on some of my models: trait HasHashedID { public static function findByHashOrFail($hash) { $id = dehash($hash); return self::findOrFail($id); } } What would be the correct way to test this?

ignaciodev's avatar
ignaciodev's avatar ignaciodev3yrs agoTesting
4
1
Last reply by ignaciodev 3yrs ago
ignaciodev's avatar

How to test Elloquent local scope coming from trait?

Hello! How can I test local scopes that are coming from a trait? This is the trait: trait HasHashedID { public static function dehashID(string $hashedID):string { return Hashids::decode($hashedID)[0]; } public function scopeFindByHashedID(Builder $query, string $hashedID):self { return $query->find(self::dehashID(hashedID: $hashedID));

ignaciodev's avatar
ignaciodev's avatar ignaciodev3yrs agoTesting
6
2
Last reply by ignaciodev 3yrs ago
harishp's avatar

Test Cache in Laravel 8

How to test Cache::remember() without logger?

harishp's avatar
harishp's avatar harishp3yrs agoLaravel
12
1
Last reply by harishp 3yrs ago
Yonibrese's avatar

Writing to the CLI while a dusk test is running

Hi, quick question. while I am running a Dusk test, is there a way to print a string to the CLI?

Yonibrese's avatar
Yonibrese's avatar Yonibrese3yrs agoLaravel
0
1
EverdevFR's avatar

API and Web on 2 different test addresses (same for deployment)

Hello, I'm developing an API and a web application with Laravel 9. I'm currently using Laragon on my development computer and I have several questions... :) How to change the test address of my API: "127.0.0.1:8000/api/" by "api.myapp.test/"? How do I change the test address of my app: "127.0.0.1:8000/" to "app.myapp.test/"? Apart from t

EverdevFR's avatar
EverdevFR's avatar Sinnbeck3yrs agoLaravel
9
1
Last reply by Sinnbeck 3yrs ago
jrdavidson's avatar

Geneating A View for a Test

What I'm attempting to do is test that inside of my Livewire Type component when the type property is changed (wired to an id of an element in form) that it will load the correct view partial underneath it. If I run the test as it will send an error saying that the view doesn't exist which makes sense to me being a factory-generated view. What would be the preferred to test thi

jrdavidson's avatar
jrdavidson's avatar jrdavidson3yrs agoTesting
7
1
Last reply by jrdavidson 3yrs ago
LaraNewDev's avatar

Change database just for one test (SQLite to MySQL)

Hi all, (this thread is not about setting one database for test and another for development) I am using SQLite for testing. Everything is nice but one thing: I use one package that performs a query not supported by SQLite. One option that I have tested succesfully is changing phpunit.xml configuration to use a MySQL database during testing (separate database than dev database).

LaraNewDev's avatar
LaraNewDev's avatar LaraNewDev3yrs agoTesting
3
1
Last reply by LaraNewDev 3yrs ago
Takeshi's avatar

Laravel: how to write test for route Marco, Middleware and model binding

I build a simple way to identify tenant with subdomain: for example: user1.example.com, the tenant will be user1. On the other hand, if user1 does not exist, the user1.example.com will response 404. I define a Marco in service provider like following: public function register() { $this->app->singleton('tenancy', function (Application $app) { return new Tenancy

Takeshi's avatar
Takeshi's avatar martinbean3yrs agoLaravel
1
1
Last reply by martinbean 3yrs ago
gizmojo's avatar

How to run migrations in a test?

Within a package test, how would I handle the migration files that are in .php.stub format? I want to avoid duplicating them to tests folder. protected function defineDatabaseMigrations() { $this->loadLaravelMigrations(); $this->loadMigrationsFrom(__DIR__ . '/database/migrations'); }

gizmojo's avatar
gizmojo's avatar gizmojo3yrs agoTesting
1
1
Last reply by gizmojo 3yrs ago
longestdrive's avatar

Test a laravel job calls another class

Hi. I'm trying to test that a job calls another class and am confused about the approach to take: My job simply calls a class to handle the type of email to send to a user. Here's my job: class SendFixtureReminderEmailJob implements ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; /** * The number of times the job may be attempted.

longestdrive's avatar
longestdrive's avatar longestdri...3yrs agoTesting
0
1
deshiloh's avatar

Unit test with BelongsTo return null

Hi, I'm trying to make a Unit Test on my service, I have a method in my service class who is doing this : private function generateTitle(): string { if ($this->forSecretary) { return sprintf( 'RESERVATION MOTOBLEU Course n°%s - %s / %s', $this->reservation->reference, ucfirst($this->reservation-

deshiloh's avatar
deshiloh's avatar deshiloh3yrs agoTesting
0
1
PhantomWalrus's avatar

How to test Lumen API when retrieving the logged in user's ID in controller constructor?

I'm trying to test CRUD operations for my Lumen controllers. The constructor for each controller looks similar to this: private $loggedInUserId; public function __construct(Request $request) { $this->loggedInUserId = $request->user()->userId; } And here's my test: public function testShowOneItemReturnsOnePayroll() { $this->withoutMiddleware();

PhantomWalrus's avatar
PhantomWalrus's avatar PhantomWal...3yrs agoTesting
2
5
Last reply by PhantomWalrus 3yrs ago
raajkumarpaneru's avatar

The test is not passing.

I have written a test for password reset with token. /** @test */ public function user_can_reset_password_with_password_reset_token() { $this->withoutExceptionHandling(); $user = User::factory()->create(); $user->password = Hash::make('old-password'); $user->save(); $response = $this->postJson('/api/password-reset

raajkumarpaneru's avatar
raajkumarpaneru's avatar raajkumarp...3yrs agoTesting
2
1
Last reply by raajkumarpaneru 3yrs ago
netdjw's avatar

Route list contain route but in test I get 404 error

I have this code in my web.php: Route::middleware('auth:sanctum')->group(function () { Route::prefix('webshop')->group(function () { Route::get('basket', [BasketController::class, 'show'])->name(RouteName::BASKET_SHOW); }); }); In the controller: public function show(PublicViewBasketRequest $request) { // ... } And in my test file:

netdjw's avatar
netdjw's avatar fylzero3yrs agoTesting
3
1
Last reply by fylzero 3yrs ago
kayaker323's avatar

Laravel dusk - won't run via sail dusk or php artisan test

I'm having some issues and have exhausted my research. My challenges are as follows: sail dusk hangs and doesn't complete. My only browser test is: <?php namespace Tests\Browser; use Laravel\Dusk\Browser; use Tests\DuskTestCase; class ExampleTest extends DuskTestCase { /** * A basic browser test example. * * @return void */ public function test

kayaker323's avatar
kayaker323's avatar shamaseen3yrs agoTesting
6
1
Last reply by shamaseen 3yrs ago
Daniel-Pablo's avatar

How to test a job?

Hello Laracaster, how I can test this??? it('dispatch and user and change his name', function () { UserName::dispatch($this->user, 'Andrew'); $newName = $this->user->refresh()->name; expect($newName)->toBe("Andrew"); }); So far it works, but this is the thing I can't wrap my head on 1- I can't work on my TEST-DB, I got to work in my officia

Daniel-Pablo's avatar
Daniel-Pablo's avatar Arius Tigg...3yrs agoFeedback
1
1
Last reply by Arius Tigger 3yrs ago
farshadf's avatar

laravel parallel test cant create the database

i am trying to run laravel feature tests in parallel mode as it is in document . my phpunit.xml is configed as below : <php> <env name="APP_ENV" value="testing"/> <env name="BCRYPT_ROUNDS" value="4"/> <env name="CACHE_DRIVER" value="array"/> <env name="

farshadf's avatar
farshadf's avatar farshadf3yrs agoLaravel
2
1
Last reply by farshadf 3yrs ago
Randy_Johnson's avatar

Creating a test but unsure how to collect answers

I am stumped, I am using radio buttons, but radio buttons just returns 'radionbutton' => 'on'. Can anyone think of a quick easy solution to the problem at hand. Database +------------+-----------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +------------+-----------------+------+-----+---------+------

Randy_Johnson's avatar
Randy_Johnson's avatar Randy_John...3yrs agoGeneral
1
1
Last reply by Randy_Johnson 3yrs ago
felixele217's avatar

Ignore FormRequests authorize in Test Class

Hey guys, is there a way how I can ignore the FormRequests authorize()-method while testing. For example my authorize method looks like: (I am using Laravel-permissions from Spatie) public function authorize() { return Auth::user()->can('add entities to site'); } And because I am using Spatie, I do not always want to create the necessary permission and a

felixele217's avatar
felixele217's avatar Sinnbeck3yrs agoTesting
3
1
Last reply by Sinnbeck 3yrs ago
MohcinBN's avatar

Test update method

Hello Devs, I'm just trying to be familiar with testing in Laravel, so I have a function to update data here is: public function isPublished(Request $request, $id) { $changeStatus = Post::FindOrFail($id); if ($changeStatus->status == 1) { $changeStatus->status = 0; } else { $changeStatus->status = 1; } // dd($changeStatus);

MohcinBN's avatar
MohcinBN's avatar tykus3yrs agoLaravel
5
1
Last reply by tykus 3yrs ago
FounderStartup's avatar

How to test google maps api on local

How to test google maps api on local environment ? I have tried all the options :)

FounderStartup's avatar
FounderStartup's avatar Nihir3yrs agoLaravel
5
1
Last reply by Nihir 3yrs ago
BernardoBF4's avatar

Is my feature test actually a unit test?

Hello, people. I have written two tests: one that makes a post request to an endpoint and awaits for a specific response containing status and message; and another one making the exact same request, but instead of await a response, it verifies if the database has the data matching what I just sent. Both these test are feature tests, and so far I have no unit test in my applicat

BernardoBF4's avatar
BernardoBF4's avatar BernardoBF...3yrs agoTesting
9
1
Last reply by BernardoBF4 3yrs ago
ReyesHatrinak's avatar

test artisan command laravel 9

I'm trying to write a test command in Laravel 9. In the below code the new user will create successfully But after creating need to redirect the Dashboard page public function test_an_action_that_requires_authentication() { $user = $this->artisan('make:user',[ 'name' => "username", 'email' => "useremail", 'password' => Str::random(8) ]); } How to

ReyesHatrinak's avatar
ReyesHatrinak's avatar Sinnbeck3yrs agoLaravel
2
1
Last reply by Sinnbeck 3yrs ago
FvsJson's avatar

Unit test all validation checks...?

I just wandering when writing unit test and lets say you have 3 types of validation on a field ie, required, number and lets say number bigger than x. Do you write tests for every single validation rule? If so that means unit testing can balloon into crazy amounts...

FvsJson's avatar
FvsJson's avatar FvsJson3yrs agoCode Review
6
1
Last reply by FvsJson 3yrs ago
netdjw's avatar

How to test @section result in View Component

I have this code in my awesome.blade.php what belongs to AwesomeComponent.php: @section('scripts') <script type="text/javascript"> var myCarousel = document.querySelector('#carousel-{{ $banner->id }}') var carousel = new bootstrap.Carousel(myCarousel) </script> @endsection // here is some other HTML codes How should I test the

netdjw's avatar
netdjw's avatar netdjw3yrs agoTesting
4
1
Last reply by netdjw 3yrs ago
JohnRugen's avatar

Seperate Test Suites & Seeders in Laravel/PhpUnit

Hi, Is it possible to run a set collection of test suites & seeders within Laravel? For example, i have one codebase for a project which is home to different clients. Each of these clients have different requirements, so the tests are going to differ, along with the seeder. How can I package these tests so that I can can run one set without running them all? I understand we

JohnRugen's avatar
JohnRugen's avatar JohnRugen3yrs agoLaravel
0
1
wipflash's avatar

Create a unit test for construct

I am using Mockery for the mocking and I am unable to test these three methods. I am using phpseclib3 as a third-party package and I am always getting phpseclib3\Exception\NoKeyLoadedException : Unable to read key. I am trying to mock this class but always fail. <?php namespace App\Services; use phpseclib3\Crypt\Common\AsymmetricKey; use phpseclib3\Crypt\PublicKeyLoader; u

wipflash's avatar
wipflash's avatar wipflash3yrs agoTesting
8
1
Last reply by wipflash 3yrs ago
Daniel-Pablo's avatar

TEST - Pest and Queues question

Hi, I am trying to find more information about creating pest tests, and testing QUEUES, in my case I am testing with reds and I want to read more about it... someone can point me to a good place? my goal is to test the JOBS dispatch, like dispatch that job using pest and then make the asserts that actually the job was executed and working after the QUEUE: WORKERS done the job t

Daniel-Pablo's avatar
Daniel-Pablo's avatar Arius Tigg...3yrs agoTesting
2
1
Last reply by Arius Tigger 3yrs ago
KodaC's avatar

Update Seeder (Spatie Permission) and run only in test environment

I add my permissions via a seeder: Permission::create(['name' => 'user_view']); Permission::create(['name' => 'user_create']); Permission::create(['name' => 'user_edit']); Role::create([ 'name' => 'admin' ])->givePermissionTo([ 'user_view', 'user_create', 'user_edit', ]); During the first installation or during a test, I create the tables with ph

KodaC's avatar
KodaC's avatar KodaC3yrs agoLumen
0
1
Shivamyadav's avatar

why my test throws an error?

showing this error and first test is passing true why error :( $ pf ProjectsTest PHPUnit 9.5.26 by Sebastian Bergmann and contributors. .EE 3 / 3 (100%) Time: 00:00.886, Memory: 32.00 MB There were 2 errors: 1) Tests\Feature\ProjectsTest::test_a_project_requires_a_title Error: Object of type Tests\Feature\Proje

Shivamyadav's avatar
Shivamyadav's avatar Shivamyada...3yrs agoTesting
2
1
Last reply by Shivamyadav 3yrs ago
Idearia's avatar

How to test method for object not accessible in the test

Hello everyone. Let's say I have a class like this: class User { public string $name; public static function create(string $name): self { $user = new self(); return $user->setName($name); } public function setName(string $name): self { $this->name = $name; return $this; } } I want to test that if I call User

Idearia's avatar
Idearia's avatar Idearia3yrs agoTesting
15
6
Last reply by Idearia 3yrs ago
ranjitkatariya's avatar

Cannot use object of type Illuminate\Support\Facades\Config as array error while running test commad with coverage report

I have one project with Laravel 9 and I am performing testing with coverage report on it, The test cases successfully passed but I'm getting the below error, and if I remove --coverage-html tmp/coverage from command it's working fine. It means this error are occurring while generating a coverage report. COMMAND: XDEBUG_MODE=coverage ./vendor/bin/phpunit --coverage-html tmp/cove

ranjitkatariya's avatar
ranjitkatariya's avatar AungHtetPa...3yrs agoTesting
1
1
Last reply by AungHtetPaing__ 3yrs ago
Jonjie's avatar

Generating new test with --unit flag is not importing the correct TestCase Class

Why laravel is using the use PHPUnit\Framework\TestCase; when generating unit test instead of using the use Tests\TestCase; when running php artisan make:test ExampleTest --unit command? I just got an error with undefined method withoutExceptionHandling() and found out that it is not importing the correct class. It was working before, but not in laravel v9. Any reason why?

Jonjie's avatar
Jonjie's avatar Jonjie3yrs agoTesting
20
1
Last reply by Jonjie 3yrs ago
arielenter's avatar

Making a test for the “string” validation in Laravel

When thinking about the purpose of the “string” validation, I immediately think about how html forms are capable of sending files. In that case, the “string” validation does really make sense to me. Using the UploadedFile, I’m able to make a test in the lines of “x field can’t be a file”. Meanwhile, when testing the “email” validation, I simply sent a wrongly formatted string a

arielenter's avatar
arielenter's avatar arielenter3yrs agoTesting
4
1
Last reply by arielenter 3yrs ago
sazvader's avatar

How to test that a job was dispatched from running a command?

I am trying to test that a job was dispatched from running a command. But, the test is failing with The excepted job was not dispatched exception. Below is what my test looks like. public function it_dispatches_a_job() { Bus::fake(); $records = $this->user->records; $this->artisan('run-job'); Bus::assertDispatched(function (Exam

sazvader's avatar
sazvader's avatar sazvader3yrs agoTesting
2
1
Last reply by sazvader 3yrs ago
BernardoBF4's avatar

Test not covering all my code

When writing tests Uncle Bob says we should only write the minimum of code to make the test pass. In my case bellow where I have the test, controller and service, it is not what happened, but I don't know how to make it different. As you can see, my test tests if a logged user can create a group: it's simply the action of storing a group (name, status and relation to a modules

BernardoBF4's avatar
BernardoBF4's avatar Sinnbeck3yrs agoTesting
2
1
Last reply by Sinnbeck 3yrs ago
BernardoBF4's avatar

Unit and Feature test for Services

I have a feature test where I post some data to an API route and validate the result. This API has its controller which calls a service method. The test is presented bellow, with the controller and service following. My question is: if I have a feature test, should I have a unit test to test the behaviour of the service method? This is because in the test bellow, I am testing t

BernardoBF4's avatar
BernardoBF4's avatar BernardoBF...3yrs agoTesting
0
1
kleninmaxim's avatar

PhpUnit test Method was expected to be called 1 times, actually called 0 times.

I have class that extend Memcached: <?php namespace Src\Databases; class Memcached extends \Memcached { private string $prefix = 'prefix'; public function __construct(array $services = ['127.0.0.1']) { parent::__construct(); foreach ($services as $service) $this->addServer($service, 11211); } public function setData(str

kleninmaxim's avatar
kleninmaxim's avatar Klenin3yrs agoTesting
3
1
Last reply by Klenin 3yrs ago
Nelwhix's avatar

How to test a php api with Pestphp

I am trying to test endpoints on my plain php api. In a laravel project you can do something like: test('app runs' , function () { $this->get('/')->assertResponse(200); }) On my plain php project I am getting this error: Call to undefined method 'get" on Testcase

Nelwhix's avatar
Nelwhix's avatar Nelwhix3yrs agoTesting
0
1
FvsJson's avatar

Unit test escapeWhenCastingToString issue

Hi all im writing a unit test to check that the view has the collection data #TEST $appliedUsers = AppliedJobPosts::query() ->where('job_posts_id', $jobPost->id) ->with('user', function ($query) { $query->select('id', 'name', 'surname'); }) ->latest('created_at') ->limit(5) ->get(); Li

FvsJson's avatar
FvsJson's avatar FvsJson3yrs agoTesting
5
1
Last reply by FvsJson 3yrs ago
BernardoBF4's avatar

Naming a test and witing what it says.

I am currently learning TDD and I found that one of the biggest difficulties is o know if you are testing what your test says you are. For example, I have a test bellow that states I am testing a group has many modules and its code simply adds modules to a group and then checks if every module is really a module. public function a_group_has_many_modules() { $modules = Mod

BernardoBF4's avatar
BernardoBF4's avatar tykus3yrs agoTesting
4
1
Last reply by tykus 3yrs ago
pl-asander's avatar

Laravel + Vite Error: Cannot test case insensitive FS, CLIENT_ENTRY does not point to an existing file

Hi together! I have a huge problem here. My Vite isn't running anymore. For example, if I create a new Laravel-Breeze project and run "vite build" or "npm run dev" I get this error: failed to load config from /Users/jannik/Dropbox/Mein Mac (Air-von-Jannik)/Desktop/Code/#Portfolio/ChefsMate/vite.config.js error when starting dev server: Error: cannot test ca

pl-asander's avatar
pl-asander's avatar pl-jgoette3yrs agoVite
5
1
Last reply by pl-jgoette 3yrs ago
Catalinul's avatar

Laravel 9 Test with transaction freezes

So I have a problem with a functional test, I am using RefreshDatabase trait. The database is PostgreSQL, everything is ran with docker. The problem is that I have two methods that use $this->beginDatabaseTransaction() inside each method at the top and when I try to see if the test passes, everything freezes. No output back, no error nothing, it just stalls. I remove the $th

Catalinul's avatar
Catalinul's avatar Catalinul3yrs agoLaravel
4
1
Last reply by Catalinul 3yrs ago
laracoft's avatar

Capture the output of `artisan test`

Is there a way to capture the output of artisan test to a file? I tried to specify in my phpunit.xml <logging> <text outputFile="phpunit.txt"/> </logging> But it only caught the following instead of the test names and results (by nuno) in detail. ............................................................... 63 / 100 ( 63%) .......

laracoft's avatar
laracoft's avatar laracoft3yrs agoTesting
4
1
Last reply by laracoft 3yrs ago
Smiffy's avatar

Best way to test file creation

I am creating a command in a package which ultimately installs a migration. What I am having trouble with is testing that the file exists and the contents of that file. I don't really want to have to physically write the file to an arbitrary location and clean up if I can help it. My command (just the important bit): ... use Illuminate\Filesystem\Filesystem; ... public function

Smiffy's avatar
Smiffy's avatar martinbean3yrs agoLaravel
3
1
Last reply by martinbean 3yrs 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.