Can I ignore specific migrations when running Laravel unit tests - php

When running tests in Laravel (php artisan test), I get an error 'duplicate column name: created_at'. This only occurs when i have field additions in the migrations directory. Am i able to ignore specific files when running Laravel tests? Or is there another way to get round this issue?
migrations:
if i just have this table, the tests work fine:
2021_06_18_134444_create_users_tables.php
after creating this migration, the tests fail:
2021_07_08_135544_add_timestamps_to_all_tables.php
a simple test:
use RefreshDatabase;
public function test_redirect_to_home_page_after_login()
{
$user = User::factory()->make([
'name' => 'Test',
'email' => 'test#hotmail.com',
'password' => bcrypt('123456')
]);
$response = $this->post('login', [
'name' => 'Test',
'email' => 'test#hotmail.com',
'password' => '123456'
]);
$response->assertRedirect('/');
$response->assertSessionHasErrors();
}

Related

Trying to get property 'id' of non-object Laravel error

I am working on someone else code in a Project and when I try to run the php artisan migrate I am encountering an error!
class SeedAdminUser extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
// seed admin user
$admin = User::create([
'name' => 'Admin',
'email' => 'admin#admin.se',
'password' => Hash::make('password'),
'plan_id' => null,
]);
$admin->assignRole(['administrator', 'company']);
$plan = Plan::find(1);
Subscription::create([
'user_id' => 1,
'plan_id' => $plan->id,
'starts_at' => Carbon::now(),
'ends_at' => $plan->interval == 'monthly' ? Carbon::now()->addMonth() : Carbon::now()->addMonths(12),
]);
}
I am getting an error because of this line 'plan_id' => $plan->id,
Here is the Error message -
ErrorException
Trying to get property 'id' of non-object
at database/migrations/2021_06_04_055759_seed_admin_user.php:34
30|
31| $plan = Plan::find(1);
32| Subscription::create([
33| 'user_id' => 1,
> 34| 'plan_id' => $plan->id,
35| 'starts_at' => Carbon::now(),
36| 'ends_at' => $plan->interval == 'monthly' ? Carbon::now()->addMonth() : Carbon::now()->addMonths(12),
37| ]);
38| }
1 database/migrations/2021_06_04_055759_seed_admin_user.php:34
Illuminate\Foundation\Bootstrap\HandleExceptions::handleError("Trying to get property 'id' of non-object", "/Applications/MAMP/htdocs/iSurvey/database/migrations/2021_06_04_055759_seed_admin_user.php", [Object(App\User)])
+21 vendor frames
23 artisan:37
Illuminate\Foundation\Console\Kernel::handle(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
Any Idea what is wrong with that line 'plan_id' => $plan->id, and how to fix it
This is because there is no records in plan model,
First check if records exists in plan model
dd($plan);
or
$plan = $plan ? $plan->id : '';
The problem is exactly what the error says. $plan is not an object, so trying to access a propriety on it result in an error.
Why is $plan not an object? Because Plan::find(1); cannot find a plan with an id of 1. $plan is probably null so you're effectively running null->id.
Since you're running migrations, you might want to make sure this code runs after your plans table is populated. I would give it a shot with php artisan migrate:fresh --seed (warning: this will empty your db tables and then repopulate them with migrations/seeders) or seeding in general.
Consider also using findOrFail instead of find to throw an exeception if the model is not found, since your subsequent code in this example depends on the model being found.
Make sure your plans are seeded before this migration runs. It's safer to use findOrFail instead. This way, you'll know the instant a plan isn't found.

Show error of two strings are equal in unit testing

I have created a small Laravel project and I am applying unit testing on my project. When I fill wrong credentials in function, it doesn't redirect to the login page and shows error on terminal saying Failed asserting that two strings are equal. Here is my code...
$credentials = [
'email' => 'test#gmail.com',
'password' => 'wrongcode'
];
$this->post('/login', $credentials)->assertRedirect('/login');
But when i change assertRedirect('/login') to assertRedirect('/') , it works fine
$credentials = [
'email' => 'test1234#gmail.com',
'password' => '98756412'
];
$this->post('/login', $credentials)->assertRedirect('/');
assertRedirect checks two string, one of them is an argument of method, 2nd is redirect path. Looks like everything works fine. You write a test, test failed, you have feedback to improve application. In that case, the redirect path is different than expected by you.
There should be 2 different methods for an individual scenario like below.
public function testCorrectCredential() {
$credentials = [
'email' => 'test1234#gmail.com',
'password' => '98756412'
];
$this->post('/login', $credentials)->assertRedirect('/');
}
public function testInCorrectCredential() {
$credentials = [
'email' => 'incorrect#gmail.com',
'password' => '98756412'
];
$this->post('/login', $credentials)->assertRedirect('/incorrect-url');
}

Laratrust attachRole returns 404 error on staging

I am using the Laratrust package for my roles management. Everything worked fine on my local developement. However, I've tried to upload my project to my server. Now, if I want to attach or detach a role, my application just redirects to a 404 error page.
What is going on?
This occures on registration, this is my registration logic:
myController.php
protected function create(array $data)
{
$user = User::create([
'firstname' => $data['firstname'],
'surname' => $data['surname'],
'email' => $data['email'],
'gender' => $data['gender'],
'password' => Hash::make($data['password']),
]);
$user->attachRole('user');
$verifyUser = \App\VerifyEmail::create([
'user_id' => $user->id,
'token' => str_random(40)
]);
Mail::to($user->email)->send(new VerifyMail($user, $verifyUser));
return $user;
}
If i remove the $user->attachRole, everything works fine.
I am not getting any errors, just the 404 page. How can I fix this?
I've created a new application key, I have run all my migrations and installed all composer packages.

Laravel AuthController not updating function body

For a school project I am trying to remove Eloquent from the core of my project (have to work directly with DB, cannot use ORM).
I am now trying to modify the create function of the AuthController, but it does not seem to be updating. (Using XAMPP with PHP7.)
As you can see I tried to replace the User::create default with the DB::insert statement inside of AuthController's create function.
protected function create(array $data)
{
return DB::insert('INSERT INTO users (firstname,lastname,birthday,gender,email,password) values(?,?,?,?,?,?)',
array(
$data['firstname'],
$data['lastname'],
$data['birthday'],
$data['gender'],
$data['email'],
bcrypt($data['password'])
)
);
// OLD FUNCTION BODY:
/*return User::create([
'firstname' => $data['firstname'],
'lastname' => $data['lastname'],
'birthday' => $data['birthday'],
'gender' => $data['gender'],
'email' => $data['email'],
'password' => bcrypt($data['password'])
]);*/
}
But now I keep getting:
FatalThrowableError in AuthController.php line 71: Fatal error: Call to undefined method App\User::create()
I believe that the function needs more than DB::insert, as it says, that it should return a new instance of the User object, but at the moment I cannot even test what this would do as it is still trying to call the old function body. I have even deleted the User::create section alltogether.
Is this a XAMP thing? I had no problem updating and saving other files of this project, but this controller does not make it through it seems like.
Try to clean Laravel cache. Then use this:
return DB::insert(array(
'firstname' => $data['firstname'],
'lastname' => $data['lastname'],
'birthday' => $data['birthday'],
'gender' => $data['gender'],
'email' => $data['email'],
'password' => bcrypt($data['password'])
)
);
If you will still get the error, please post contents of 71th line of AuthController.php
You are returning two entirely different thing.
return DB::insert
vs
return User::create
See what User::create returns and go from there.

Factories on Laravel 5.2 not working as expected

I have a very strange problem with Laravel 5.2 factories.
I have recently upgraded from Laravel 5.1 to 5.2 following the upgrade guide on the Laravel website. All works as exepected except one factory. Yes the others work ok. Here are two of the factories:
$factory->define(App\Client::class, function (Faker\Generator $faker) {
return [
'name' => $faker->company,
'building' => $faker->buildingNumber,
'street' => $faker->streetName,
'town' => $faker->city,
'postcode' => $faker->postcode,
'country' => 'UK',
'telephone' => $faker->phoneNumber,
'fax' => $faker->phoneNumber,
];
});
$factory->define(App\Shift::class, function (Faker\Generator $faker) {
return [
'client_id' => $faker->numberBetween($min = 1, $max = 15),
'user_id' => $faker->numberBetween($min = 1, $max = 15),
'start' => $faker->dateTimeBetween($startDate='now', $endDate='+60 days'),
'public' => $faker->boolean(),
];
});
The top factory works no problem but the second one doesn't run at all cause my db seed to throw an error because its not populating the client_id which is a foreign key.
The only difference between the two models is that the client model doesn't use timestamps where as the shift model does. Other than that they are identical.
I will keep plugging away but any help to shed light on this would be greatly received.
When you add your own constructor, are you making sure to call parent::__construct() inside it?

Categories