I have an issue with running migrations while making a test. I have migrations in different places. User migrations depend on Company migrations but each time I run tests I have an error that table 'companies' doesn't exist.
Code from test class:
protected function setUp()
{
parent::setUp();
$this->artisan('migrate', [
'--path' => ['Modules/Company/Database/Migrations',
'Modules/User/Database/Migrations'],
]);
}
protected function tearDown()
{
$this->artisan('migrate:reset', [
'--path' => ['Modules/User/Database/Migrations',
'Modules/Company/Database/Migrations'],
]);
parent::tearDown();
}
Can anyone help me, please.
Thanks!
Problem was in two places:
1) option --path was provided as an array(but no warnings are displayed);
2) command migrate:reset(it resets ALL the migrations using provided --path so the error 'Undefined index: create_company_table' happens).
Final version.
protected function setUp()
{
parent::setUp();
$this->artisan('migrate', [
'--path' => 'Modules/Company/Database/Migrations',
]);
$this->artisan('migrate', [
'--path' => 'Modules/User/Database/Migrations',
]);
}
protected function tearDown()
{
$this->artisan('migrate:rollback', [
'--path' => 'Modules/User/Database/Migrations/',
]);
$this->artisan('migrate:rollback', [
'--path' => 'Modules/Company/Database/Migrations/',
]);
parent::tearDown();
}
Related
I'm having a strange problem with my Laravel feature tests.
I have a createTeam method that creates a factory record and persists it in memory-database.
public function createTeam(): static
{
$this->team = Team::factory()->create([
'name' => $this->user->name . ' Team',
]);
$this->team->assignMember($this->user, TeamRoleTypes::OWNER);
return $this;
}
Then I go on and try to test an action.
public function testUserCanDeleteItsOwnTeam()
{
$this->createTeam();
$this
->useToken()
->deleteJson(route('team.delete', ['team' => $this->team->id]), [
'name' => 'Second team',
])
->assertOk();
}
However, the response says "No query results for model [App\Models\Team] e99a7514-58e2-4d29-91f2-f0c3a034a419". When I check the same model for existence in the same test by using something like Team::find("e99a7514-58e2-4d29-91f2-f0c3a034a419") and it says it's there!
Does anyone have any idea why such thing happens?
Turns out, the problem lied with the factory and the mystical behavior of Laravel/PHPUnit/Memory DB or whatever...
What happened was caused by the autogenerated factory class trying to fill the timestamp fields manually as can be seen below:
class TeamFactory extends Factory
{
protected $model = Team::class;
public function definition(): array
{
return [
'id' => Str::uuid(),
'name' => $this->faker->name(),
'deleted_at' => Carbon::now(),
'created_at' => Carbon::now(),
'updated_at' => Carbon::now(),
];
}
}
The last three definitions were causing the cancer and now everything is working as expected after deletion of these little buggers.
I get the message Call to a member function beginTransaction() on null when importing data from "Maatwebsite\Excel\Excel" using laravel 8.0 and MongoDB.
Export is ok, I've already tried to set transaction handler to 'null' and php artisan config:clear and php artisan config:cache but with no luck.
here's my controller
public function store(UserLoadRequest $request)
{
$request->authorize();
$validated = $request->validated();
//dd($request->file('usersList'));
//dd($validated['usersList']->getPathname());
Excel::import(new UsersImport, $request->file('usersList'));
return redirect()->back()->with('success', 'Utenti caricati');
}
and here my import function
class UsersImport implements ToModel, WithHeadingRow
{
public function model(array $row)
{
return new User([
'descrizione' => $row['descrizione'],
'username' => $row['username'],
'password' => Hash::make($row['password']),
'meccanografico' => $row['meccanografico'],
'role_id' => $row['role_id'],
]);
}
}
The mongo db driver does not support transactions. Disable them in the config file. First publish it with php artisan vendor:publish --provider="Maatwebsite\Excel\ExcelServiceProvider" --tag=config and then change the handler
'transactions' => [
'handler' => 'null', //was db. Set to null
],
Solution Source link
I have a laravel app with passport installed to manage api auth. I'm trying to write some tests but I'm unable to create a Client as per the docs on laravel. I've googled similar SO answers but they all suggest using setUp and tearDown methods which I am doing. When I run the test I get
InvalidArgumentException
Unable to locate factory for [Laravel\Passport\Client].
How can I get this to work?
Below is my code. I have included the Client model from the passport package and I am using the setUp and tearDown methods as suggested in similar SO answers.
I've tried composer dump-autoload and php artisan config:cache.
use Laravel\Passport\Passport;
use Laravel\Passport\Client;
...
use RefreshDatabase;
protected function setUp(): void
{
parent::setUp();
}
protected function tearDown(): void
{
parent::tearDown();
}
public function testAPIEndpointFailsWhenNoParamIsSet()
{
Passport::actingAsClient(
factory(Client::class)->create(),
['*']
);
$response = $this->postJson('/api/endpoint', [
'param' => ''
]);
$response->assertStatus(401)
->assertJson(['message' => 'Unauthenticated.']);
}
passport client factory should be existed on publishing ...
if it did not .... make it your self:
from : here
use Laravel\Passport\Passport;
use Laravel\Passport\Client;
$factory->define(Client::class, function (Faker $faker) {
return [
'user_id' => null,
'name' => $faker->company,
'secret' => Str::random(40),
'redirect' => $faker->url,
'personal_access_client' => 0,
'password_client' => 0,
'revoked' => 0,
];
});
Trying to use an in-memory testing database for my unit tests. It seems that it can't even run the migrations, because the migrations table does not exist.
Here is my code:
abstract class TestCase extends BaseTestCase
{
use DatabaseMigrations;
public function setUp()
{
parent::setUp();
// use testing database
$this->setUpDatabase();
}
public function setUpDatabase()
{
$this->app['config']->set('database', [
'default' => 'testing',
'connections' => [
'testing' => [
'driver' => 'sqlite',
'database' => ':memory:',
],
],
]);
}
This gives me the error:
PDOException: SQLSTATE[HY000]: General error: 1 no such table: migrations
Not only that, but it also seems to be running migrations on my main database.
I am having this on my laravel project and i want to add more methods to the exept array. And i could not figure it out how i should write it?
public function __construct()
{
$this->middleware('auth', [ 'except' => 'index' ]);
}
Just add such an array like that:
public function __construct()
{
$this->middleware('auth', [ 'except' =>['index','fooAction'] ]);
}
You can see more about here: https://laravel.com/docs/5.1/controllers#controller-middleware
try this
public function __construct()
{
$this->middleware('auth', [ 'except' => ['index','home'] ]);
}