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

jesse_orange_newable's avatar

Relationship is null in test

In my application a User can make an InvestmentApplication. These models are related to each other like so: /** * Get this user's applications * * @return void */ public function applications() { return $this->hasMany(InvestmentApplication::class, 'user_id', 'id'); } /** * Get the user associated with the investment application. */ public function user() {

jesse_orange_newable's avatar
jesse_orange_newable's avatar bugsysha6yrs agoTesting
19
1
Last reply by bugsysha 6yrs ago
jove's avatar

UnitTests how to get ID of created model or wipe DB each test?

So my current issue is that I hardcode the ID $response = $this->post(route('admin.books.store'), $attributes); $response->assertRedirect(route('admin.books.show', 1)); Now this started to fail after I added a bunch more tests because when it arrives at this it fails to match the ID of 1 is equal to 7. How can I get the ID of the new book created in the post or have a cl

jove's avatar
jove's avatar Nakov6yrs agoTesting
3
1
Last reply by Nakov 6yrs ago
rbur0425's avatar

Test Model From Job Class PHPUnit Mockery

How do I mock the markshipped method on the ebayOrders model? I am testing that the job handle() method works correctly. My current test the markshipped method still runs. Job - class ProcessOrderJob implements ShouldQueue { public function handle() { $DB = ''; $Controller = ''; if (strcmp($this->username, 'user1') === 0) { $DB = '\App

rbur0425's avatar
rbur0425's avatar bugsysha6yrs agoTesting
11
1
Last reply by bugsysha 6yrs ago
marcel158's avatar

Cypress E2E Tests to use the test database

I am using cypress.io for e2e testing. In my tests I am creating, updating and deleting data and this does all happen on the same database that I'm working with when I'm developing. And this idea is getting worse when you think about running your tests on a staging or production environment. For my phpunit backend tests, I have set to use my test database by adding this line in

marcel158's avatar
marcel158's avatar marcel1586yrs agoTesting
0
1
Corbin's avatar

How do I test encrypted database fields?

I'm encrypting database fields using a custom Encryptable trait: Encryptable.php <?php namespace App; use Illuminate\Support\Facades\Crypt; trait Encryptable { public function getAttribute($key) { $value = parent::getAttribute($key); if (in_array($key, $this->encryptable)) { $value = Crypt::decrypt($value); return $value;

Corbin's avatar
Corbin's avatar bugsysha6yrs agoTesting
6
2
Last reply by bugsysha 6yrs ago
farshadf's avatar

simple test in laravel in create method

i want to simply test my model to see if it can be created or not here is what i tried : public function it_test_insert_model(){ // $this->actingAs(User::class); $wish = factory(Model::class)->create(); $this->post('/model/create',$wish->toArray()); $this->assertEquals(1,Model::all()->count()); } now my problem is every

farshadf's avatar
farshadf's avatar tykus6yrs agoLaravel
8
1
Last reply by tykus 6yrs ago
ilyavorozhbit's avatar

Mock in feature test

Hi all! I'm writing a feature test, and in that test I need mock one method of some service, and then I need make $this->actingAs(...)->post(), which will use that service. But I don't know how to do it. Is it possible? Thank you

ilyavorozhbit's avatar
ilyavorozhbit's avatar Sergiu176yrs agoTesting
1
1
Last reply by Sergiu17 6yrs ago
sohexaxok's avatar

Write test for resource

Hi, I have a resource for my API endpoint with a resource collection, but I want to test some logic for this resource collection. How can I write a test for this? This is my resource class class CardCollection extends ResourceCollection { public $resource; public function __construct(Collection $cardCollection) { parent::__construct($cardCollection);

sohexaxok's avatar
sohexaxok's avatar bobbybouwm...6yrs agoTesting
1
1
Last reply by bobbybouwmann 6yrs ago
tobyreed's avatar

Set expiry of CSRF token in PHPUnit test

Hello, We have an issue in our PROD where users/we will get a 419 status code (CSRF token expired) from what I understand. I am trying to debug this and make a test from it too. But I am wondering is there a way to expire the CSRF token on a test, I have googled it but cannot find anything of actual value that could help :/

tobyreed's avatar
tobyreed's avatar Nakov6yrs agoTesting
3
1
Last reply by Nakov 6yrs ago
dingo_d's avatar

Test for user creation fails on validation

I have created a user creation screen and in my UserController I have a store method /** * Store a newly created users in a database. * * @param Request $request Incoming request * * @throws ValidationException * * @return mixed */ public function store(Request $request) { $this->validate($request, [ 'na

dingo_d's avatar
dingo_d's avatar dingo_d6yrs agoTesting
6
1
Last reply by dingo_d 6yrs ago
Markk's avatar

VScode phpunit test

Untill a while ago i could do the unit testing fine with shortcut which i assigned but now it only works if i manually type in the console php vendor/phpunit/phpunit/phpunit. When i place the cursor inside or on the method name and try to do the test using the keybind it opens a small window in vscode to configure tasks? https://imgur.com/a/s6qqXSQ Has anyone encoutered a simil

Markk's avatar
Markk's avatar Markk6yrs agoTesting
5
1
Last reply by Markk 6yrs ago
yoeriboven's avatar

Removing a config entry for a test

I'm adding a feature to an existing package which will add a new config key/value. Current users don't have this item since this record doesn't exist yet. To make sure this is not a breaking change I want to test the package when the record is not set. app('config')->set('shield.enabled', null); sets the enabled key in the shield config file to null but doesn't remove the ke

yoeriboven's avatar
yoeriboven's avatar yoeriboven6yrs agoTesting
2
1
Last reply by yoeriboven 6yrs ago
VertexBuffer's avatar

Mocking a file in a Storage for a PHPUnit test?

I'm writing a test for one of my Form's store methods, and basically I have a file upload with it. I upload the file via ajax into a temp directory on the server and then when the form is submitted, I transfer it from temp into s3 storage. I'm having some issues mocking this for my test. I was hoping someone could provide an example of how I could create a temp image file in my

VertexBuffer's avatar
VertexBuffer's avatar ronon6yrs agoCode Review
2
1
Last reply by ronon 6yrs ago
GodziLaravel's avatar

How to login then go to specific link to test ?

Hello , In my test I would like to login as user then get specific url status ! public function test_links() { $this->post('/login', [ 'email' => '[email protected]', 'password' => 'password', ]) ->get('/myprofile') ->assertStatus(200); }

GodziLaravel's avatar
GodziLaravel's avatar mostafalar...6yrs agoTesting
6
1
Last reply by mostafalaravel 6yrs ago
GodziLaravel's avatar

is it possible to test if all routes are redirected to login page when user is not logged-id ?

Hello , Here bellow I made a test to know if a non-loged user when he request / is redirected to the login page . the question is : this test is only for / route , is there any way to test the rest of routes without typing theme all ? someting like $this->get('/*') ? public function test_if_user_is_not_logged_must_redirect_to_login_page(){ $this->get('/'

GodziLaravel's avatar
GodziLaravel's avatar bugsysha6yrs agoTesting
5
1
Last reply by bugsysha 6yrs ago
wBailie's avatar

Inconsistent StaleElementReferenceException and NoSuchElementException test errors with Laravel Dusk

I am frequently running a test suite of around 250 tests. Everytime I run this test suite I am getting inconsistent errors returned for what seems like different tests each time. An example of inconsistent errors that are returned: Facebook\WebDriver\Exception\StaleElementReferenceException: stale element reference: element is not attached to the page document (Session info:

wBailie's avatar
wBailie's avatar bugsysha6yrs agoTesting
1
1
Last reply by bugsysha 6yrs ago
mcbates's avatar

Factories do not run in unit test files (but in feature tests, after update 5.4>6)

My factories do not get found in unit test files, but only in feature tests. Here is the exact same test with the respective class infos. I recently upgraded the app form Laravel 5.4 to 6.0. Maybe I need to adjust some test base classes or the like. Factory <?php /** @var \Illuminate\Database\Eloquent\Factory $factory */ use Faker\Generator as Faker; $factory->define(A

mcbates's avatar
mcbates's avatar mcbates6yrs agoGeneral
6
1
Last reply by mcbates 6yrs ago
mcbates's avatar

Accessor does not render in Blade when running feature test

On my Note model, I have an Eloquent accessor getTypeDescriptionAttribute. It shows correctly in my UI, an unit test is passing, but the feature test that asserts that it sees the retrieved value fails. Why does the accessor not work in the Blade when being rendered in the test? Any help on how to debug this? Model: public function getTypeDescriptionAttribute() { return NoteT

mcbates's avatar
mcbates's avatar mcbates6yrs agoGeneral
2
1
Last reply by mcbates 6yrs ago
esmaill23's avatar

LARAVEL TRIGGER MIGRATION PROBLEM ON TEST ENVIRONMENT

hello i have created a laravel migration as like below. it works on migrate on mysql in product env but not work on sqlite in testing env . thank you : public function up() { \Illuminate\Support\Facades\DB::unprepared('CREATE TRIGGER after_insert_price AFTER INSERT ON `movie_prices` FOR EACH ROW BEGIN IF((SELECT status from agreements wh

esmaill23's avatar
esmaill23's avatar Tray26yrs agoLaravel
5
1
Last reply by Tray2 6yrs ago
Jegan's avatar

Laravel Load / Stress Test - Failed

Hi All, I am quite new to Laravel, I have a simple Laravel application which has 19 REST service endpoints which will be consumed by Mobile Application. I have tested the REST endpoints using J Meter to identify the concurrent users that I can have in my server. I have tested in two servers one had 512 MB RAM & Single core processor and I have ran the same load test on my l

Jegan's avatar
Jegan's avatar Cronix6yrs agoLaravel
2
1
Last reply by Cronix 6yrs ago
abkrim's avatar

[SOLVED] Upgrade system to PHP 7.4 fail only test for users

Hi. I'm desesperate. Today upgrade my develop system to PHP 7.4. Well after upgrade, run test and I see fails on Users tests. I run test by folder (models) Domain, Mailboxes. All work fine Run test for users, and I get error. Error? Only user nas a problem, and there're using mysql database, instead sqlite in memory. A simple test for verify problem function a_super_admin_can

abkrim's avatar
abkrim's avatar abkrim6yrs agoPHP
11
3
Last reply by abkrim 6yrs ago
nolannordlund's avatar

V-for isn't rendering items in my test

I have a simple component that should show a list of items as well as a new item button <template> <div> <ul ref="item-list"> <li v-for="item in items" :key="item.id" id="item.id">{{ item.title }}</li> <li ref="new-item" @click="$emit('newItem')">N

nolannordlund's avatar
nolannordlund's avatar bugsysha6yrs agoTesting
4
1
Last reply by bugsysha 6yrs ago
farshadf's avatar

how to test 50k users in laravel application

hi , i have an application and i want to test to see if it can handle 50k users or not , how can i test it is there any good tool for laravel to test application capacity ?? thanks

farshadf's avatar
farshadf's avatar farshadf6yrs agoLaravel
6
1
Last reply by farshadf 6yrs ago
Catalinul's avatar

Factory can't be seen in unit test.

This is how my ModelFactory.php looks: <?php /** @var \Illuminate\Database\Eloquent\Factory $factory */ use App\User; use Faker\Generator as Faker; use Illuminate\Support\Str; $factory->define(User::class, function (Faker $faker) { return [ 'name' => $faker->name, 'email' => $faker->unique()->safeEmail, 'email_verified_at' =&g

Catalinul's avatar
Catalinul's avatar mayanksdud...4yrs agoLaravel
11
1
Last reply by mayanksdudakiya 4yrs ago
LearningLaravelYai's avatar

Detect that laravel is running test in controllers?

Hi, when laravel run tests, both unit test and feature tests, does is sets any global variables, that I can detect other places in the application? I'm not interested in the .env trick. But would like to know if there are other ways to detect, that the application is in test mode? Currently I think of setting a global variable in my test.. but maybe there is already something?

LearningLaravelYai's avatar
LearningLaravelYai's avatar Cronix6yrs agoTesting
1
1
Last reply by Cronix 6yrs ago
Corbin's avatar

Do you guys test auth?

When working on authentication and adding various fields like username and slug to your users table do you guys test it? Why or why not? I'm trying to get better at development and I want to do this project that I have properly. Should I skip the tests for this knowing that so many things will change later in the project? Or maybe not? Just looking for insights. Thanks guys.

Corbin's avatar
Corbin's avatar Corbin6yrs agoTesting
3
1
Last reply by Corbin 6yrs ago
MarkOmeje's avatar

TEST ERROR

I'm getting this error in my test 1) Tests\Feature\ManageProjectTest::guests_cannot_manage_projects Response status code [200] is not a redirect status code. Failed asserting that false is true. C:\xampp\htdocs\laravel\birdboard\vendor\laravel\framework\src\Illuminate\Foundation\Testing\TestResponse.php:148 C:\xampp\htdocs\laravel\birdboard\tests\Feature\ManageProjectTest.php:

MarkOmeje's avatar
MarkOmeje's avatar bugsysha6yrs agoRequests
3
1
Last reply by bugsysha 6yrs ago
vasilukwolf's avatar

Class and method don't have connect in test folder

Last time I'm working https://laracasts.com/series/build-a-laravel-app-with-tdd 17, and I have trouble with connecting the class or method https://github.com/vasilukwolf/TDDLaravelApp/runs/333732102 Run vendor/bin/phpunit PHPUnit 8.4.3 by Sebastian Bergmann and contributors. ................E... 20 / 20 (100%) Time: 981 ms, Memory:

vasilukwolf's avatar
vasilukwolf's avatar bugsysha6yrs agoLaravel
1
1
Last reply by bugsysha 6yrs ago
Blindacme's avatar

How to test page speed on backend

I'm trying to find out how to test the page speed on the backend (auth) pages of my app. I've tried GTMetrix but I don't think this will work for testing page speed on a protected auth page. Any help would be appreciated!

Blindacme's avatar
Blindacme's avatar kobear6yrs agoTips
1
1
Last reply by kobear 6yrs ago
labib47's avatar

Unit Test observer model

Hi , im using model observer , i want to create a unit test where i can test each of function in observer . Somehow i cannot fake the event in the observer . I try to call like we fake a event class , somehow it does not work . Here is my code for observer : - public function saved(Education $education) { //update form status if(Auth::user()->form_education == null

labib47's avatar
labib47's avatar Sergiu176yrs agoLaravel
1
1
Last reply by Sergiu17 6yrs ago
tayebhbabaei's avatar

how writhing test for tow button for one form

hlpe me to add test for tow button on one form and i don't wath testing?

tayebhbabaei's avatar
tayebhbabaei's avatar Tray26yrs agoLaravel
1
1
Last reply by Tray2 6yrs ago
successdav's avatar

Test failed, Mail not sending

trying to send a mail but the the mails is not sending, test fails Test Class /** @test */ public function an_email_is_sent_if_unable_to_assign_systemNo() { Mail::fake(); factory('App\Subscription', 15)->create(); $user = $this->signIn(); $admin = factory('App\User')->states('administrator')->create(); $course =

successdav's avatar
successdav's avatar Sinnbeck6yrs agoLaravel
14
1
Last reply by Sinnbeck 6yrs ago
exSnake's avatar

In Tinker is True in test is false

This is my DB structure: permissions permission_role roles role_user users I have this Test Method: /** @test */ public function an_operator_can_view_changes(){ $user = factory('App\User')->create(); $role = Role::firstOrCreate(['name' => 'Operator']); $permission = Permission::firstOrCreate(['name' => 'view_changes']); $role->gi

exSnake's avatar
exSnake's avatar exSnake6yrs agoLaravel
7
1
Last reply by exSnake 6yrs ago
rawnato's avatar

Laravel 6 Test After Redirect

Hello All I have this test /** * @test */ public function testUserCanUpdateProfileData() { $this->login(); $new = ['name' => $this->faker->name, 'email' => $this->faker->safeEmail]; $this->post('/profile', $new)->assertRedirect('/profile')->assertSee($new['name'])->assertSee($new['email']); } This test not working, do you know

rawnato's avatar
rawnato's avatar Tray26yrs agoTesting
3
1
Last reply by Tray2 6yrs ago
NOHHANGYEOL's avatar

If the test fails because the comments generated in the post and the comments in the test are different during the test.

If the test fails because the comments generated in the post and the comments in the test are different during the test. How do I match the data in the test case? <?php namespace Tests\Feature; use Tests\TestCase; class ParticipateInForumTest extends TestCase { /** @test */ public function an_authenticated_user_may_participate_in_forum_t

NOHHANGYEOL's avatar
NOHHANGYEOL's avatar NOHHANGYEO...6yrs agoTesting
4
1
Last reply by NOHHANGYEOL 6yrs ago
NOHHANGYEOL's avatar

Testcase Error in Test Progress

The word is translated. https://laracasts.com/series/lets-build-a-forum-with-laravel/episodes/4?autoplay=true Watching the above lecture my PC window10 -> ubuntu install /** @test */ public function an_authenticated_user_may_participate_in_forum_threads () { $this->be(factory('App\User')->create()); $thread = factory('App\Thread')->create();

NOHHANGYEOL's avatar
NOHHANGYEOL's avatar fylzero6yrs agoTesting
4
1
Last reply by fylzero 6yrs ago
jgravois's avatar

Failing Test and I am Lost

Am I doing something wrong here? I can't figure out WHY this test is failing. (I still have SO MUCH to learn about testing) /** @test */ public function user_can_update_return_admin_notes () { $user = factory(User::class)->create(); $rma = factory(ReturnsRequest::class)->create([ 'initiator_id' => 1, 'company_name' => 'Fru

jgravois's avatar
jgravois's avatar jgravois6yrs agoTesting
8
1
Last reply by jgravois 6yrs ago
davewood's avatar

laravel test "remembers" api_token authentication for unauthenticated followup request

I see this behaviour only with the laravel test system, cannot reproduce when i make the same sequence of requests with curl or browser. get('/api/foo?api_token='.$wrong_token, 401) // ok ... 401 get('/api/foo?api_token='.$correct_token, 200) // ok ... 200 get('/api/foo?api_token='.$wrong_token, 401) // NOTOK ... app returns 200 if i make the same requests with curl from a re

davewood's avatar
davewood's avatar davewood6yrs agoTesting
4
1
Last reply by davewood 6yrs ago
MarkOmeje's avatar

PhpUnit TEST

Please how can i run test on windows. My test command "/vendor/bin/phpunit /tests/feature/ProjectTest.php" is failing. Please help.

MarkOmeje's avatar
MarkOmeje's avatar devoracle3yrs agoTesting
15
1
Last reply by devoracle 3yrs ago
ya-ya-it's avatar

Mass email send and test

Hello! I'm taking over the development of a contest project. This project requires to send a lot (200K-3M) emails per day. For these purposes, the company is using SendGrid API. But what happened last time is they sent 3m emails at once, SendGrid rejected it, this created an infinity loop, customers started to receive 10-15 same emails, the reputation becomes 0 and so one. I wa

ya-ya-it's avatar
ya-ya-it's avatar siangboon6yrs agoLaravel
2
1
Last reply by siangboon 6yrs ago
deepu07's avatar

PHPUnit Test

Hi Guys here is my phpunit.xml file <php> <env name="APP_ENV" value="testing"/> <env name="BCRYPT_ROUNDS" value="4"/> <env name="CACHE_DRIVER" value="array"/> <env name="MAIL_DRIVER" value="array"/> <env name="QUEUE_CONNEC

deepu07's avatar
deepu07's avatar deepu076yrs agoLaravel
12
1
Last reply by deepu07 6yrs ago
bhushan's avatar

AssertSee multiple thing in phpunit test

/** @test */ public function it_shows_top_ten_profiles_according_to_the_reputation_points_earned() { $users = create('App\User', [], 20); $sortUsers = $users->sortByDesc('reputation')->pluck('name')->take(10)->toArray(); $this->get(route('profiles.index')) ->assertSee($sortUsers[0]) ->assertSee($sortUsers[1]

bhushan's avatar
bhushan's avatar Sinnbeck6yrs agoTesting
3
1
Last reply by Sinnbeck 6yrs ago
tobz.nz's avatar

Mocking in feature test

Hi, I'm having an issue with mocking in a feature test - maybe this is bad practice(is mocking more a unit test thing?) Anyway, the mock seems to be setup in the test context, but then the concrete class is returned from ioc in the app when the route is called. function testExample() { $this->mock(MyClass::class, function ($mock) { $mock->shouldReceive('someM

tobz.nz's avatar
tobz.nz's avatar tobz.nz6yrs agoTesting
9
1
Last reply by tobz.nz 6yrs ago
gazd1977's avatar

Accessing Cookie in PHPunit Test

Hi Everyone, I'm trying my hand with phpunit and trying to test cookies, but i am having difficulty accessing the cookie to check its value. In my test i post to a controller that performs some logic, queues a cookie and then redirects. I then access another controller via a get request where i am trying to access the cookie to compare its value against a token stored in my da

gazd1977's avatar
gazd1977's avatar gazd19776yrs agoTesting
2
1
Last reply by gazd1977 6yrs ago
jgravois's avatar

How to test extra values in the ->pivot()

I have an additional column in my permission_user table of permission_level. I am trying to TTD a helper method but don't know how to test the ->pivot(). This is where I am: /** @test */ public function a_user_can_be_assigned_a_permission () { $user = create(User::class); $permission = create(Permission::class, [ 'name' => 'Returns',

jgravois's avatar
jgravois's avatar jgravois6yrs agoTesting
2
1
Last reply by jgravois 6yrs ago
VertexBuffer's avatar

What is the correct way to write a test when paginating the output?

I've been trying to write some tests and if I just use a standard query like; Model::latest()->get() and write a test like so; $models = factory(Model::class, 20) ->create() ->sortByDesc('created_at'); $this->getJson('/api/models') ->assertOk() ->assertJson($models->toArray()); It works fine.

VertexBuffer's avatar
VertexBuffer's avatar VertexBuff...6yrs agoCode Review
0
1
Ranx99's avatar

How to test redis queue connection?

I am using "redis" to mange my queues phpunit.xml: <server name="QUEUE_CONNECTION" value="redis"/> But in the following test the queue's connection name returns "null": /** @test */ public function is_pushed_to_queue() { Queue::fake(); $user = factory(User::class)->create(); $user->notify(

Ranx99's avatar
Ranx99's avatar Arius Tigg...3yrs agoTesting
5
1
Last reply by Arius Tigger 3yrs ago
Ranx99's avatar

How to test a queued notification?

I have a WelcomeNotification which implements ShouldQueue class WelcomeNotification extends Notification implements ShouldQueue { use Queueable; public function via($notifiable) { return ['mail']; } public function toMail($notifiable) { // send a welcome message to the user via mailtrap } } How can I test if this notification has

Ranx99's avatar
Ranx99's avatar zaherg6yrs agoTesting
2
1
Last reply by zaherg 6yrs ago
realtebo's avatar

How to use Cypress.io to test a Laravel app?

I would like to give a try to Cypress to test a laravel ap.. Do you know a good tutorial about it? A part this, I ask you how to accomplish the 'reset' of db before each test session. I thinks it's a common problem. I have a dedicated test server with a dedicated db, so I can have a fresh copy of production with real data, then test my code in a real environment; now I register

realtebo's avatar
realtebo's avatar realtebo6yrs agoLaravel
3
1
Last reply by realtebo 6yrs ago
dembilesmana's avatar

Test the account users in the database

I want to test the account users in the database (not the users in the table). so basically I can make a database with php. how to do that in laravel?

dembilesmana's avatar
dembilesmana's avatar dembilesma...6yrs agoLaravel
4
1
Last reply by dembilesmana 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.