This is the part of testing that I do not get. What should we test and what should we not test. I mean we can't test everything right? Especially if we work an hourly freelance project, writing to test every little thing is going to cost our clients too much. Or are you showing these things as an example, like asserting that the name is 3 letters, then asserting if the name is passed, I mean you can't do this with each field right. That would be too much. But where do we draw the line?
First of all I want to appreciate because of your high quality and useful tutorials ... In this episode u wrote some tests that triggered a question that why we should test this obvious actions ? We easily run app on browser and see the results ...are these tests essential for development ?
You should write test for all actions, no matter how obvious they are. Then you can go to sleep without thinking that an error has slipped away undetected because of human error/logic/thinking process. It's a tedious work, everyone agrees, but if you are serious, you should do it.
For those who actually use MySQL as their DB and get error when trying to run tests in sqlite, I suggest to use MySQL for testing also. You need to create separate database (smth like mydatabase-test); In phpunit.xml bellow (inside tags) add: So what this does is it uses MySQL instead of sqlite. I think this is slower, but it eliminates any compatibility issues.
when I run phpunit test in console, Vendor/bin/phpunit --filter only_logged_..._list, it shows : no test executs. I finially find this problem solved method. Add test prefix to any test function in Test.php. like this : test_only_logged_..._list. It's gain the same effects as videos shows. Maybe the version of Phpunit : my version is 7.20. CHeers , hopefully helpful.
With the current version of Laravel and Telescope I see no issue with running PHPUnit. Looks like the new version of Telescope is no longer causing issues.
Dang it. Your too late for me. I've been binge watching PHPUnit videos at Laracasts. Thanks for making these videos nonetheless! I'm a fan of the channel. :D
Tried adding a new test with a simple 'if string' and works. However, when I add 2nd function, it gives me an error PHP Fatal error: Cannot declare class App\Console\Commands elatationshipDaemon, because the name is already in use in ... I'm not calling this command at all, so its confusing me a lot. Code:
Before Starting this lesson, I wish to let everyone know that laravel's recent version has changed the naming standard for test cases. SO if you use: public function only_logged_in_user_can_see_customers_list() { // code here } IT WILL FAIL. It will not be detected by PHPUnit at all. The new format is that you use prefix the function name with "test" so it should be named: public function testonly_logged_in_user_can_see_customers_list() { // code here }
Again, for the windows users:cls && "./vendor/bin/phpunit" --options [NAME_OF_OPTION] although: file: phpunit.xml
// :memory: - for me doesn't work file: /tests/Features/CustomersTest.php $this->actingAs(factory(\App\User::class)->create()); // Have to add \App\Users or use App\User;
Hello. Thank you for tutorials. When testing, that user can add new customers. Wouldn't be better instead of "assertCount" to use "AssertDatabaseHas" and compare if input matches with database data?
assertDatabaseHas seems to be more geared towards ensuring the database contains specific values while count allows you to check for a specific count. assertDatabaseHas requires a table name as well as the associative data array so it would be easier to use a count in his case.
Hello, First of all thanks for your scracth tutotrial, i lean many things. I've a question, where to put logic business of my laravel application? In controller? In model? or Using design pattern repository. Thanks
That’s a great question but a difficult one to answer because there’s no single correct answer for this. The true answer is, it depends. One approach that has worked for me is, creating a directory in my app directory for project classes. This will include classes for connecting to APIs or logic specific to the project. You can then bind them into the service container and have laravel serve them up for you in the controller using dependency injection. Again, this is my approach, it doesn’t mean there aren’t 10 different ways to do it.
@@CodersTapeThanks for your rapid reply, your approche looks like java approche with service layer, anyway as you say there are many, so one more thanks. Hope that you going deep in test driven developpement because it's no easy to write test before code. Great job!!!!
Really Thank you for this tutorial. It´s one of the best I have ever watched. I got a Failure in second case testing : There was 1 failure: 1) Tests\Feature\CustomersTest::authenticated_users_can_see_the_customers_list Response status code [404] does not match expected 200 status code. Failed asserting that false is true. Any advice? Thanx
Hi I got error when I run vendor/bin/phpunit, error:"Tests\Feature\ExampleTest::testBasicTest Expected status code 200 but received 302. Failed asserting that false is true."
If your code is similar throughout all the tutorials, I think the basic idea is that visiting the customers page whilst not logged in should redirect you to the login page. I had the same error as you but set the method to $response = $this->get('/customers/show')->assertRedirect('/login'); The problem is that visiting '/customers' doesn't redirect you when logged in, '/customers/show' does. I realise your post was 6 months ago but I'm so happy I've identified and fixed something... doesn't happen often!
Tests\Feature\CustomersTest::a_customer_can_be_added_through_the_form Intervention\Image\Exception\NotReadableException: Image source not readable I get this error ..after setting up authorizationException..If anyone know the answer please share..
Hi Victor, I am messing around with the test - I tried to follow your guide but I am struggling. I added
to my phpunit.xml file and my testfile looks like this name is UserTest.php /** @test */ public function only_logged_in_users_can_see_the_dashboard() { $response = $this->get('/home')->assertRedirect('/login'); } /** @test */ public function authenticated_users_can_see_the_dashboard() { $user = factory(User::class)->create(); $this->actingAs($user); $response = $this->get('/home')->assertOk(); } If I run phpunit it gives me 1) Tests\Feature\UserTest::authenticated_users_can_see_the_dashboard Response status code [500] does not match expected 200 status code. Failed asserting that false is true. Do you have any suggestions for me? Thanks, Timo
@@CodersTape I just tried your suggestion 1) Tests\Feature\UserTest::authenticated_users_can_see_the_dashboard ErrorException: Undefined index: REMOTE_ADDR (View: /home/vagrant/code/Nathan/resources/views/layouts/app.blade.php) (View: /home/vagrant/code/Nathan/resources/views/layouts/app.blade.php) Caused by ErrorException: Undefined index: REMOTE_ADDR (View: /home/vagrant/code/Nathan/resources/views/layouts/app.blade.php) Caused by ErrorException: Undefined index: REMOTE_ADDR in my layouts/app.blade.php I have created a user menu which also includes {!! $_SERVER['REMOTE_ADDR']; !!} the show the user his IP (its a intranet project) This call creates the error. After removing this - All tests running as expected. Thanks for the advice with $this->withoutExceptionHandling(); this helped a lot finding the problem. Timo
Did you rename the ExampleTest.php file? If so, make sure that it still ends in Test.php For example, Customers.php == not valid test file name CustomersTest.php == valid name
@@CodersTape This is what I have written: class PostsTest extends TestCase { /**@test **/ public function only_logged_in_users_can_see_the_posts(){ $response = $this->get('/posts') ->assertRedirect('/login'); }
I am using mysql connection and when I set db_database to :memory: I run into error. error: Tests\Feature\CustomersTest::test_only_logged_in_users_can_see_customers_list PDOException: SQLSTATE[HY000] [1049] Unknown database ':memory:' Please help!
Hello sir, I'm getting this errors, I did exactly what you did but I still get this errors I'm working on a Windows 10 machine. This is my error when I run the first test only logged in users can see the customer list () Error message: Failed to insert that two string are equal ---expected +++Actual -'localhost/login +'localhost
It's now working. The problem was in the construction method... $this->middleware('auth')->except('index') I had to remove the except() to make it work properly. Thanks for the fast response you're the best.😀
The docs never said anything about disabling telescope. I feel sorry to those who are banging their head against the docs. I'm doubting going for docs now every time I want to learn something new.
I MISS YOUR VIDEOS SO MUCH!
I suggest a video with relationships: product, category, subcategory, ( to help for laravel eCommerce )
in laravel 7,
run "php artisan test" instead of "vendor/bin/phpunit"
Great tutorial, I suggest you to make such a integration with third-party like pusher, payment gateway and etc. Thanks a lot.
This is the part of testing that I do not get. What should we test and what should we not test. I mean we can't test everything right? Especially if we work an hourly freelance project, writing to test every little thing is going to cost our clients too much. Or are you showing these things as an example, like asserting that the name is 3 letters, then asserting if the name is passed, I mean you can't do this with each field right. That would be too much. But where do we draw the line?
First of all I want to appreciate because of your high quality and useful tutorials ... In this episode u wrote some tests that triggered a question that why we should test this obvious actions ? We easily run app on browser and see the results ...are these tests essential for development ?
You should write test for all actions, no matter how obvious they are. Then you can go to sleep without thinking that an error has slipped away undetected because of human error/logic/thinking process. It's a tedious work, everyone agrees, but if you are serious, you should do it.
Great! as Always!
It would be great to have some videos about creating a complete API with Laravel.
thanks so much for your help
For those who actually use MySQL as their DB and get error when trying to run tests in sqlite, I suggest to use MySQL for testing also.
You need to create separate database (smth like mydatabase-test);
In phpunit.xml bellow (inside tags) add:
So what this does is it uses MySQL instead of sqlite. I think this is slower, but it eliminates any compatibility issues.
Thanks, I will try this. I was still getting the error user table not found. Do you know if we should add and
@@kendallhayes4917 no, you don't need to add :memory: , because MySQL doesn't work in memory as SQLite.
I have a telescope switched on in my application, but phpunit is still working properly! Don't you know the reason Mr.Gonzalez?
The BEST as always!
when I run phpunit test in console, Vendor/bin/phpunit --filter only_logged_..._list, it shows : no test executs. I finially find this problem solved method.
Add test prefix to any test function in Test.php. like this : test_only_logged_..._list. It's gain the same effects as videos shows. Maybe the version of Phpunit : my version is 7.20. CHeers , hopefully helpful.
With the current version of Laravel and Telescope I see no issue with running PHPUnit. Looks like the new version of Telescope is no longer causing issues.
Please, give us an accounting system or ecommerce app with Laravel. Your teaching skill has no equal.
when I tried to execute "vendor/bin/phpunit" it gives me "vendor is not recognized as an internal or external command,operable program or batch file."
There is an error in that store array you have put 'active' 2 times but php unit didn't catch that mistake!
Why ?
Dang it. Your too late for me. I've been binge watching PHPUnit videos at Laracasts. Thanks for making these videos nonetheless! I'm a fan of the channel. :D
Sir please make a blog for beginners #Laravel ?
Your videos are awesome!!!
The latest commit is (e44 - Policies) on github, can you please commit your other changes. Thanks.
Tried adding a new test with a simple 'if string' and works. However, when I add 2nd function, it gives me an error
PHP Fatal error: Cannot declare class App\Console\Commands
elatationshipDaemon, because the name is already in use in ...
I'm not calling this command at all, so its confusing me a lot.
Code:
InvalidArgumentException: Unable to locate factory for [App\User].
I test API using phpunit test but i keep getting " Expected status code Ok but received 302." what is this 302 about ?
Before Starting this lesson, I wish to let everyone know that laravel's recent version has changed the naming standard for test cases. SO if you use:
public function only_logged_in_user_can_see_customers_list()
{
// code here
}
IT WILL FAIL. It will not be detected by PHPUnit at all. The new format is that you use prefix the function name with "test" so it should be named:
public function testonly_logged_in_user_can_see_customers_list()
{
// code here
}
/**
* @test
*/
Again, for the windows users:cls && "./vendor/bin/phpunit" --options [NAME_OF_OPTION]
although:
file: phpunit.xml
// :memory: - for me doesn't work
file: /tests/Features/CustomersTest.php
$this->actingAs(factory(\App\User::class)->create());
// Have to add \App\Users or use App\User;
make it sqlite
Great video
Hello. Thank you for tutorials. When testing, that user can add new customers. Wouldn't be better instead of "assertCount" to use "AssertDatabaseHas" and compare if input matches with database data?
assertDatabaseHas seems to be more geared towards ensuring the database contains specific values while count allows you to check for a specific count. assertDatabaseHas requires a table name as well as the associative data array so it would be easier to use a count in his case.
how to deploy laravel on sheared host ? Really waiting for you videos
Thank you my good sir
This video actual for laravel 8 ?
Hello,
First of all thanks for your scracth tutotrial, i lean many things. I've a question, where to put logic business of my laravel application? In controller? In model? or Using design pattern repository.
Thanks
That’s a great question but a difficult one to answer because there’s no single correct answer for this. The true answer is, it depends. One approach that has worked for me is, creating a directory in my app directory for project classes. This will include classes for connecting to APIs or logic specific to the project. You can then bind them into the service container and have laravel serve them up for you in the controller using dependency injection.
Again, this is my approach, it doesn’t mean there aren’t 10 different ways to do it.
@@CodersTapeThanks for your rapid reply, your approche looks like java approche with service layer, anyway as you say there are many, so one more thanks. Hope that you going deep in test driven developpement because it's no easy to write test before code. Great job!!!!
You’re right. It’s very difficult to imagine your code before writing it but once it clicks, it’s eye opening how much better your code gets.
I'm getting the following error:
Error: Call to undefined method Tests\Unit\CustomersTest::get()
Maybe i comment to much late but i've Database [:memory:] not configured. error
Really Thank you for this tutorial. It´s one of the best I have ever watched.
I got a Failure in second case testing :
There was 1 failure:
1) Tests\Feature\CustomersTest::authenticated_users_can_see_the_customers_list
Response status code [404] does not match expected 200 status code.
Failed asserting that false is true.
Any advice? Thanx
404 is page doesn't exist. Check the logs.
Hi I got error when I run vendor/bin/phpunit, error:"Tests\Feature\ExampleTest::testBasicTest
Expected status code 200 but received 302.
Failed asserting that false is true."
If your code is similar throughout all the tutorials, I think the basic idea is that visiting the customers page whilst not logged in should redirect you to the login page. I had the same error as you but set the method to $response = $this->get('/customers/show')->assertRedirect('/login'); The problem is that visiting '/customers' doesn't redirect you when logged in, '/customers/show' does. I realise your post was 6 months ago but I'm so happy I've identified and fixed something... doesn't happen often!
Tests\Feature\CustomersTest::a_customer_can_be_added_through_the_form
Intervention\Image\Exception\NotReadableException: Image source not readable
I get this error ..after setting up authorizationException..If anyone know the answer please share..
Can you make more videos, please !!!
i want laravel shoping cart tutorial so bad. 😢
Hi Victor,
I am messing around with the test - I tried to follow your guide but I am struggling.
I added
to my phpunit.xml file and my testfile looks like this name is UserTest.php
/** @test */
public function only_logged_in_users_can_see_the_dashboard()
{
$response = $this->get('/home')->assertRedirect('/login');
}
/** @test */
public function authenticated_users_can_see_the_dashboard()
{
$user = factory(User::class)->create();
$this->actingAs($user);
$response = $this->get('/home')->assertOk();
}
If I run phpunit it gives me
1) Tests\Feature\UserTest::authenticated_users_can_see_the_dashboard
Response status code [500] does not match expected 200 status code.
Failed asserting that false is true.
Do you have any suggestions for me?
Thanks, Timo
Yes. Inside of your test add the following line
$this->withoutExceptionHandling();
Then run your test again, that will give you a real error.
@@CodersTape thanks for the quick reply I will test this tomorrow just left work :)
@@CodersTape I just tried your suggestion
1) Tests\Feature\UserTest::authenticated_users_can_see_the_dashboard
ErrorException: Undefined index: REMOTE_ADDR (View: /home/vagrant/code/Nathan/resources/views/layouts/app.blade.php) (View: /home/vagrant/code/Nathan/resources/views/layouts/app.blade.php)
Caused by
ErrorException: Undefined index: REMOTE_ADDR (View: /home/vagrant/code/Nathan/resources/views/layouts/app.blade.php)
Caused by
ErrorException: Undefined index: REMOTE_ADDR
in my layouts/app.blade.php I have created a user menu which also includes
{!! $_SERVER['REMOTE_ADDR']; !!} the show the user his IP (its a intranet project) This call creates the error. After removing this - All tests running as expected.
Thanks for the advice with $this->withoutExceptionHandling(); this helped a lot finding the problem.
Timo
I'm getting a no tests found when I try to run the first test. Do you have any idea why this may be the case ?
Did you rename the ExampleTest.php file? If so, make sure that it still ends in Test.php
For example, Customers.php == not valid test file name
CustomersTest.php == valid name
And make sure that your test methods in the file have the /** @test **/ at the top
@@CodersTape Yes, I have it set as PostsTest.php and it seems to still give me the same problem.
Do you have the annotation on the function? Or does it start with test?
@@CodersTape This is what I have written:
class PostsTest extends TestCase
{
/**@test **/
public function only_logged_in_users_can_see_the_posts(){
$response = $this->get('/posts')
->assertRedirect('/login');
}
You can use the "testdox" option for detailed test reports.
www.amitmerchant.com/make-phpunit-test-reports-detailed-using-textdox/
when will you bring for us a full project?
Already working on it for the channel.
Also, I just authored a 4.5 hour course for freeCodeCamp. It will be posting this week.
What's included in ?
@@MuhammadAdnan-gx6rd that's an instagram clone project from scratch.
@@CodersTape Cool waiting,,,,,,,,,sir
Thank you bro
I am using mysql connection and when I set db_database to :memory: I run into error.
error:
Tests\Feature\CustomersTest::test_only_logged_in_users_can_see_customers_list
PDOException: SQLSTATE[HY000] [1049] Unknown database ':memory:'
Please help!
Change the connection to sqlite not mysql
Haha, this one overwritten my whole existing database with laravel migration data. Not happy.
whoa nice, is better coding while doing phpunit
I did'nt get green after making telescope disable.???
Try stopping the artisan serve command and starting it again.
PDOException: SQLSTATE[HY000]: General error: 1 Cannot add a NOT NULL column with default value NULL
When you’re adding a column after the fact, you need to have a default value
Hello sir,
I'm getting this errors, I did exactly what you did but I still get this errors I'm working on a Windows 10 machine.
This is my error when I run the first test only logged in users can see the customer list ()
Error message:
Failed to insert that two string are equal
---expected
+++Actual
-'localhost/login
+'localhost
it looks like it's not redirecting properly. Make sure that you are setting the auth middleware for authentication.
Ok sir. I will give it another try and I will get back to you. Thanks for the reply
It's now working. The problem was in the construction method... $this->middleware('auth')->except('index') I had to remove the except() to make it work properly. Thanks for the fast response you're the best.😀
@@zeusgolohor8409 awesome! Glad to hear you are back on track.
Please push this testing code to git
The docs never said anything about disabling telescope. I feel sorry to those who are banging their head against the docs. I'm doubting going for docs now every time I want to learn something new.
How cool u speak.