PHPUnit tests failing after adding a ViewServiceProvider for sharing data to views - laravel

I am relatively new to testing so please forgive me if this a stupid question.
All my tests are failing after I added a ViewServiceProvider to share data with the views.
The error is:
Illuminate\Database\QueryException : SQLSTATE[HY000]: General error: 1 no such table: policies (SQL: select "name", "slug" from "policies")
My tests are making use the the refresh database trait:
namespace Tests\Feature;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
class ExampleTest extends TestCase
{
use RefreshDatabase;
...
}
Here is an example of the ViewServiceProvider:
namespace App\Providers;
use App\Models\Policy;
use Illuminate\Support\ServiceProvider;
class ViewServiceProvider extends ServiceProvider
{
public function register(): void{...}
public function boot(): void
{
view()->share('policies', Policy::all(['name', 'slug']));
}
}
Every works when browsing the site on front end. Am i missing something? Why are the tests failing?
I will appreciate suggestions on how to make the tests pass.
Edit
It makes total sense what #Donkarnash said but it's also confusing because according to the docs:
So, what if we need to register a view composer within our service provider? This should be done within the boot method. This method is called after all other service providers have been registered, meaning you have access to all other services that have been registered by the framework
See https://laravel.com/docs/8.x/providers#the-boot-method

I found the solution. Creating a view composer solved the problem.
namespace App\Http\View\Composers;
use App\Models\Policy;
use Illuminate\View\View;
class PolicyComposer
{
public function compose(View $view): void
{
$view->with('policies', Policy::all(['name', 'slug']));
}
}
Then I referenced the composer in the ViewServiceProvider
namespace App\Providers;
use App\Models\Policy;
use Illuminate\Support\ServiceProvider;
class ViewServiceProvider extends ServiceProvider
{
public function register(): void{...}
public function boot(): void
{
view()->composer('*', PolicyComposer::class);
}
}

Related

Laravel Livewire error when I add a constructor to call a service class

I've got a piece of code I want to reuse. I've read this Laravel cleaner code article and this other Laravel Services Pattern article, where I have realized I can reuse code in several places of the application by using services classes.
In this case, I created a new MyService class, inside a new folder app/Services/MyService.
namespace App\Services;
class MyService
{
public function reuse_code($param){
return void;
}
}
The problem comes when I want to call the class through the constructor inside a Livewire class component, as follows:
<?php
namespace App\Http\Livewire;
use App\Services\MyService;
use Livewire\Component;
use Livewire\WithPagination;
class LivewireTable extends Component
{
use WithPagination;
private $myClassService;
public function __construct(MyService $myService)
{
$this->myClassService = $myService;
}
public function render()
{
$foo = $this->myClassService->reuse_code($param);
return view('my.view',compact('foo'));
}
}
The error displayed is the following:
Argument 1 passed to App\Http\Livewire\LivewireTable::__construct()
must be an instance of App\Services\MyService, string given
(However, If I use a trait, there are no problems. But I am afraid then my traits collide as previous experiences)
How do I fix it? What am I missing?
Livewire's boot method Runs on every request, immediately after the component is instantiated, but before any other lifecycle methods are called
Here's the solution worked for me.
Solved
Just like #IGP said, reading in the livewire docs it says:
In Livewire components, you use mount() instead of a class constructor
__construct() like you may be used to.
So, my working code is as follows:
<?php
namespace App\Http\Livewire;
use App\Services\MyService;
use Livewire\Component;
use Livewire\WithPagination;
class LivewireTable extends Component
{
use WithPagination;
private $myClassService;
public function mount(MyService $myService)
{
$this->myClassService = $myService;
}
public function render()
{
$foo = $this->myClassService->reuse_code($param);
return view('my.view',compact('foo'));
}
}

Override vendor model in laravel 6.X

I want to override the model inside of vendor. I tried bellow code. But not working.
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
public function register()
{
//
}
public function boot()
{
$this->app->bind('VendorName\Models\User', 'App\Models\User');
}
}
Extending model is not an option, as i have to override all controller change model path and write all methods again, its not worth it.
Binding a class in the container like this isn't going to override direct references to the class you're trying to override if the object isn't being resolved using the service container.
So for example, something like $user = new \VendorName\Models\User; isn't going to be affected because it's simply not using the container.
I think the only sensible solution is to refactor your code so you're using a class that extends the base User class.

Laravel Testing/phpunit, Too few arguments passed when using dependency injection

I'm trying to create a simple test with Laravel. My test code is as below;
<?php
namespace Tests\Feature;
use Tests\TestCase;
use Illuminate\Foundation\Testing\WithFaker;
use Illuminate\Foundation\Testing\RefreshDatabase;
use App\Http\Controllers\Abc\AbcController;
class AbcTest extends TestCase
{
/**
* A basic test example.
*
* #return void
*/
private $abcController;
public function __construct (AbcController $abcController) {
$this->abcController = $abcController;
}
public function testExample()
{
$this->assertTrue(true);
}
However, when i run the test, i'm hitting this error,
PHP Fatal error: Uncaught ArgumentCountError: Too few arguments to function Tests\Feature\abc::__construct(), 0 passed in /var/www/nex/backend/vendor/phpunit/phpunit/src/Framework/TestSuite.php on line 151 and exactly 1 expected in /var/www/nex/backend/tests/Feature/abc.php:28
I've been using this method of performing dependency injections for the rest of my project. I'm not sure why its not working on this particular code.
All help is appreciated.
Thanks!
Check https://laravel.com/docs/5.8/testing you should not use Dependency Injection on controller. Instead you should call the endpoint.
Example
<?php
namespace Tests\Feature;
use Tests\TestCase;
use Illuminate\Foundation\Testing\WithFaker;
use Illuminate\Foundation\Testing\RefreshDatabase;
use App\Http\Controllers\Abc\AbcController;
class AbcTest extends TestCase
{
public function testExample()
{
$response = $this->get('/url');
$response->assertOk();
}
}

Dependency resolving with App::make not working when bind is done by a provider in Laravel

I'm using Laravel 5.2. I tried to resolve a dependency in Laravel out of the IOCContainer as follows.(with App::make method)
App/FooController.php:-
<?php
namespace App\Http\Controllers;
use App\Bind\FooInterface;
use Illuminate\Support\Facades\App;
class FooController extends Controller
{
public function outOfContainer(){
dd(App::make('\App\bind\FooInterface')); // Focus: program dies here!!
}
}
Bindings for the FooInterface done in the AppServiceProvider as follows
App/Providers/AppServiceProvider.php:-
<?php
namespace App\Providers;
use App\Bind\Foo;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
public function register()
{
$this->app->bind('\App\Bind\FooInterface', function() {
return new Foo();
});
}
}
Structure of the Foo class as follows.
App/Bind/Foo.php:-
<?php
namespace App\Bind;
class Foo implements FooInterface {
}
Structure of the FooInterface interface as follows:-
<?php
namespace App\Bind;
interface FooInterface {
}
Then I created a route as follows.
Route::get('/outofcontainer', 'FooController#outOfContainer');
But when I navigate to this route it throws an exception with the error text:
BindingResolutionException in Container.php line 748:
Target [App\bind\FooInterface] is not instantiable.
What is going wrong with this?
How to use App:make() with the AppServiceProvider?
In your service provider, you're binding the string '\App\Bind\FooInterface'. In your controller, you're attempting to make the string '\App\bind\FooInterface'. These strings are not the same, as they have differing cases (Bind vs bind). Since the strings are not the same, Laravel cannot find the binding in the container.
Correct the casing in your make statement and it should work:
dd(App::make('\App\Bind\FooInterface'));

Grouping event registrations on a service provider

I want to define a service provider that registers events. So have done the following (taken from a book)
<?php
namespace MyApp\Providers;
use Illuminate\Support\ServiceProvider;
class EventsProvider extends ServiceProvider
{
public function boot()
{
Event::listen('some.event', function($parameter)
{
// Handle the event..
});
}
}
Then I added it to the provider array.
But when I execute the code I get the following error
implement the remaining methods
(Illuminate\Support\ServiceProvider::register)
It compels me to declare a register() method.
When I add to the EventsProvider class a method named register() (without implementation, and just make it return null) I get the following error
Class 'MyApp/Providers/EventProvider' not found
Why is that, and how can I solve it?
You just need to declare it, because it's declared in the Interface:
<?php namespace MyApp\Providers;
use Illuminate\Support\ServiceProvider;
class EventsProvider extends ServiceProvider {
public function boot()
{
Event::listen('some.event', function($parameter)
{
// Handle the event..
});
}
public function register()
{
}
}
Then execute
composer dump-autoload --optimize
But you might also have a typo somewhere because it says Class 'MyApp/Providers/EventProviders' not found, but it should be MyApp/Providers/EventProvider.

Resources