Laravel - I have an error when I run test in laravel - laravel

I have an error when I run my test in laravel:
Illuminate\Database\QueryException: could not find driver (SQL: PRAGMA foreign_keys = ON;)
Here is the test code:
namespace Tests\Feature;
use Tests\TestCase;
use Illuminate\Foundation\Testing\RefreshDatabase;
use App\Book;
class BookReservationTest extends TestCase
{
use RefreshDatabase;
/** #test */
public function a_book_can_be_added_to_the_library()
{
$this->withoutExceptionHandling();
$response = $this->post('/books', [
'title' => 'cool book title',
'author' => 'victor'
]);
$response->assertOk();
$this->assertCount(11, Book::all());
}
}

Related

Laravel Auth::attemp() is not working, even with valid credentials

This is the unit test which I want to run. This is always failing. I have tried with wrong data. Still it fails and with correct data still it fails. Please someone help me out from this.
If anyone wants to explore more: http://github.com/PawanRoy1997/forum.git
Php Unit Test:
<?php
namespace Tests\Feature;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Auth;
use Tests\TestCase;
class UserTest extends TestCase
{
use RefreshDatabase;
/** ##test */
public function login()
{
$data = ['name'=>'some', 'email'=>'some#some.com','password'=>'password'];
User::create($data);
$this->assertTrue(Auth::attempt($data));
}
}
Output:
➜ forum git:(master) ✗ asn test
FAIL Tests\Unit\UserTest
⨯
FAIL Tests\Feature\UserTest
⨯ login
---
• Tests\Unit\UserTest >
Error
Call to a member function connection() on null
at vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php:1571
1567▕ * #return \Illuminate\Database\Connection
1568▕ */
1569▕ public static function resolveConnection($connection = null)
1570▕ {
➜ 1571▕ return static::$resolver->connection($connection);
1572▕ }
1573▕
1574▕ /**
1575▕ * Get the connection resolver instance.
+7 vendor frames
8 tests/Unit/UserTest.php:19
Illuminate\Database\Eloquent\Model::__callStatic()
• Tests\Feature\UserTest > login
Failed asserting that false is true.
at tests/Feature/UserTest.php:19
15▕ public function login()
16▕ {
17▕ $data = ['name'=>'some', 'email'=>'some#some.com','password'=>'password'];
18▕ User::create($data);
➜ 19▕ $this->assertTrue(Auth::attempt($data));
20▕ }
21▕ }
22▕
Tests: 2 failed
Time: 0.31s
➜ forum git:(master) ✗
Actually, I just figured it out that I need to hash the password while creating the user. I forgot to mention that I have updated Laravel then all of this started. In laravel 8.51, Auth::attempt checks for hashed passwords only. But in laravel 8.50 and before, it allows password to be not hashed.
<?php
namespace Tests\Feature;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Tests\TestCase;
class UserTest extends TestCase
{
/**
* A basic feature test example.
*
* #return void
*/
public function test_example()
{
$data = [
'name' => 'someone',
'email' => 'some#some.com',
'password' => Hash::make('password'),
'confirm_password' => 'password'
];
User::create($data);
$this->assertDatabaseCount('users', 1);
$this->assertTrue(Auth::attempt(['email' => 'some#some.com', 'password' => 'password']));
}
}

Laravel php testing, called undefined function?

I write a code using laravel 8 and i want to create CRUD Testing for all model so i can called it in every test case, for example I Have Operator Test that extends TestCase (crud testing master) ref : crud test, this is my Operator Test looks like,..
<?php
namespace Tests\Feature;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\WithFaker;
use Tests\TestCase;
class OperatorTest extends TestCase
{
use RefreshDatabase, WithFaker;
public function test_user_can_update_an_operator()
{
$this->setBaseRoute('master.operator');
$this->setBaseModel('App\Models\Operator');
$this->signIn();
$this->attributes = [
'username' => 'test update',
'level' => 1,
'category_id' => 1,
'password' => 'password'
];
$this->update($this->attributes);
}
}
and this is my TestCase.php looks like,...
<?php
namespace Tests;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
use App\Models\Operator;
use Illuminate\Foundation\Testing\WithFaker;
abstract class TestCase extends BaseTestCase
{
use CreatesApplication;
use RefreshDatabase;
protected $base_route = null;
protected $base_model = null;
protected function signIn($user = null)
{
$user = $user ?? Operator::factory()->create();
$this->actingAs($user);
return $this;
}
protected function setBaseRoute($route)
{
$this->base_route = $route;
}
protected function setBaseModel($model)
{
$this->base_model = $model;
}
protected function update($attributes = [], $model = '', $route = '')
{
$this->withoutExceptionHandling();
$route = $this->base_route ? "{$this->base_route}.update" : $route;
$model = $this->base_model ?? $model;
$model = create($model);
if (! auth()->user()) {
$this->expectException(\Illuminate\Auth\AuthenticationException::class);
}
$response = $this->patchJson(route($route, $model->id), $attributes);
tap($model->fresh(), function ($model) use ($attributes) {
collect($attributes)->each(function($value, $key) use ($model) {
$this->assertEquals($value, $model[$key]);
});
});
return $response;
}
}
after that when I tun php artisan test, i got an error like this :
anything worng in my codes ? i used laravel 8.
You need to initialize the model first and then call the model factory.
The create function is undefined at line 64.
Instead of
$model = create($model);
Use bellow code
$model = app()->make($model)
$model = $model::factory()->create();
More information on app()->make() and factory.

Test Case with laravel Dusk showing error 'users_email_unique'

I'm getting error as on below screenshot
Please help me i am trying and for this i have spend too much time but still issue no luck.
I am using laravel official dusk package for front-web testing. When i am running login test case its showing error "users_email_unique" which is above showing in picture. I am using use DatabaseTransactions but it is not reverting my last transaction. For this i am using test database also. Here is my my code:
<?php
namespace Tests\Browser;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Laravel\Dusk\Browser;
use Tests\DuskTestCase;
use App\User;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class LoginTest extends DuskTestCase
{
use DatabaseTransactions;
/**
* A Dusk test example.
*
* #return void
*/
public function test_I_can_login_successfully()
{
$user = factory(User::class)->create([
'email' => 'login#gmail.com',
'password' => bcrypt('password'),
]);
$this->browse(function ($browser) use ($user) {
$browser->visit('/')
->type('email', 'login#gmail.com')
->type('password', 'password')
->press('Login')
->assertSee($user->name);
});
}
}
For Dusk you cannot use use DatabaseTransactions. You need to use DatabaseMigrations instead. When you update trait then you should get rid of the error.
You have sample Dusk test in documentation and it looks like this:
<?php
namespace Tests\Browser;
use App\User;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Laravel\Dusk\Chrome;
use Tests\DuskTestCase;
class ExampleTest extends DuskTestCase
{
use DatabaseMigrations;
/**
* A basic browser test example.
*
* #return void
*/
public function testBasicExample()
{
$user = factory(User::class)->create([
'email' => 'taylor#laravel.com',
]);
$this->browse(function ($browser) use ($user) {
$browser->visit('/login')
->type('email', $user->email)
->type('password', 'password')
->press('Login')
->assertPathIs('/home');
});
}
}
As you see it's also using DatabaseMigrations trait.

Invalid Argument Exception - Laravel Unit Testing

I am running a unit test to check that
View page exists
AssertSee that text appears on the page and with a string limit
I am getting an invalid argument exception:
1) Tests\Feature\ViewAllPostTest::testCanViewAllPosts
InvalidArgumentException: You requested 1 items, but there are only 0 items available.
C:\projects\car-torque-laravel\vendor\laravel\framework\src\Illuminate\Support\Arr.php:472
C:\projects\car-torque-laravel\vendor\laravel\framework\src\Illuminate\Support\Collection.php:1486
C:\projects\car-torque-laravel\database\factories\PostFactory.php:12
C:\projects\car-torque-laravel\vendor\laravel\framework\src\Illuminate\Database\Eloquent\FactoryBuilder.php:274
C:\projects\car-torque-laravel\vendor\laravel\framework\src\Illuminate\Database\Eloquent\FactoryBuilder.php:292
C:\projects\car-torque-laravel\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Concerns\GuardsAttributes.php:122
C:\projects\car-torque-laravel\vendor\laravel\framework\src\Illuminate\Database\Eloquent\FactoryBuilder.php:300
C:\projects\car-torque-laravel\vendor\laravel\framework\src\Illuminate\Database\Eloquent\FactoryBuilder.php:219
C:\projects\car-torque-laravel\vendor\laravel\framework\src\Illuminate\Database\Eloquent\FactoryBuilder.php:178
C:\projects\car-torque-laravel\tests\Feature\ViewAllPostTest.php:19
My source code is as follows:
Test Function
namespace Tests\Feature;
use App\Post;
use Tests\TestCase;
class ViewAllPostTest extends TestCase
{
/**
* #group posts
*
* #return void
*/
public function testCanViewAllPosts()
{
//arrange
$post = factory(Post::class)->create();
//action
$response = $this->get('/posts');
//assert
$response->assertStatus(200);
$response->assertSee($post->body);
$response->assertSee(str_limit($post->body));
}
}
Factory Class
use App\Post;
use App\User;
use Faker\Generator as Faker;
$factory->define(Post::class, function (Faker $faker) {
return [
'body' => $faker->text,
'user_id' => User::all()->random()->id,
'created_at' => now(),
'updated_at' => now(),
];
});
'user_id' => User::all()->random()->id,
In the above line of your factory, you want random id form your users table. But have you created any User before running the test. At least a user should be created before creating post using post factory.

laravel Class 'App\Categories' not found

When I try to call a function with categories data $categories = Categories::all(); it returns an error that Class 'App\Categories' not found
Here is my CategoriesController code:
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller as BaseController;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
use App\Categories;
class CategoriesController extends BaseController
{
public function listcategories() {
$categories = Categories::all();
dd($categories);
return view('admin.list_categories')->with('listcategories',
$categories);
}
Here is my Categories model code ;
namespace App;
use Illuminate\Http\Request;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Input;
class Categories extends Model
{
protected $fillable = [
'title',
'description',
'flag_image',
'status'
];
const STATUSES = [
'Active' => 'Active',
'Inactive' => 'Inactive',
];
const DEFAULT_STATUS = 'Active';
/**
* Indicates if the model should be timestamped.
*
* #var bool
*/
public $timestamps = false;
public static function rules() {
return [
'title' => 'required|string|max:255',
'status' => 'required|string|in:' . implode(",", Categories::STATUSES)
];
}}
What is the problem ? I can't get it.
Because models are autoloading via composer
in some cases you need to run
composer dump-autoload after changes in order to make it work

Resources