Currently I am using many factories factory() in Test class, is there a way to reduce to 1 so I can only use factory(Something::class) in a test method?
Reason I used many because I have to pass some foreign keys.
$user = factory(User::class)->create();
$token = factory(Token::class)->create([
'user_id' => $user->id,
]);
$provider = factory(Provider::class)->create([
'user_id' => $user->id,
'token_id' => $token->id,
]);
$something = factory(Something::class)->create([
'provider_id' => $provider->id,
]);
// Now test with $something
You can use such syntax:
$factory->define(Something::class, function ($faker) {
return [
'title' => $faker->title,
'content' => $faker->paragraph,
'provider_id' => function () {
return factory(Provider::class)->create()->id;
}
];
});
$factory->define(Provider::class, function ($faker) {
$user = factory(User:class)->create();
return [
'user_id' => $user->id,
'token_id' => function () {
return factory(Token::class)->create(['user_id' => $user->id])->id;
}
];
});
and then in your tests you can only use:
$something = factory(Something::class)->create();
Be aware depending on your needs it can cause some side effects - for example when using Provider factory, user will be always created what might be fine or not depending on your tests. Of course if needed you can always created helper method that will wrap all those methods you showed and return only something and then in your test you can only use:
$something = $this->createSomething();
Related
I am testing an eager loading relationship which contains many to many relations. Right now I have the queries and attachments within the test. I'm wondering if there is a way to move them into the factory, rather than including it as part of your test. This would limit the size of the test and then these relations could be created and used every time a film factory is created.
test
public function grabFilmTest()
{
$film = factory(Film::class)->create();
$categories = Category::where('main-cat', 'Science')->where('sub-cat', 'Fiction')->first();
$languages = Languages::where('name', 'english')->first();
$film->categories()->attach($categories->id);
$film->languages()->attach($languages->id);
$response = $this->json('GET', '/film/' . $film->id)
->assertStatus(200);
$response
->assertExactJson([
'id' => $film->id,
'name' => $film->name,
'description' => $film->description,
'categories' => $film->categories->toArray(),
'languages' => $film->languages->toArray()
}
filmFactory
$factory->define(\App\Models\Film::class, function (Faker $faker){
return [
'id' => $faker->uuid,
'name' => $faker->text,
'description' => $faker->paragraph,
];
});
If anyone could help with how i could do this or an example it would be great :D
You could use factory states and factory callbacks.
$factory->define(\App\Models\Film::class, function (Faker $faker){
return [
'id' => $faker->uuid,
'name' => $faker->text,
'description' => $faker->paragraph,
];
});
$factory->define(\App\Models\Category::class, function (Faker $faker){
return [
// Category fields
];
});
$factory->define(\App\Models\Language::class, function (Faker $faker){
return [
// Language fields
];
});
$factory->afterCreatingState(\App\Models\Film::class, 'with-category', function (\App\Models\Film $film) {
$category = factory(\App\Models\Category::class)->create();
$film->categories()->attach($category->id);
});
$factory->afterCreatingState(\App\Models\Film::class, 'with-language', function (\App\Models\Film $film) {
$language = factory(\App\Models\Language::class)->create();
$film->categories()->attach($language->id);
});
Then you can use in tests like this:
public function grabFilmTest()
{
$film = factory(Film::class)->create();
$filmWithCategory = factory(Film::class)->state('with-category')->create();
$filmWithLanguage = factory(Film::class)->state('with-language')->create();
$filmWithCategoryAnLanguage = factory(Film::class)->states(['with-category', 'with-language'])->create();
// ...
}
PS: I don't recommend using existing data. From experience, I can tell you that can become really painful.
You can use factory callbacks to do it in the factory file:
<?php
use \App\Models\Film;
use \App\Models\Category;
use \App\Models\Languages;
$factory->define(Film::class, function(Faker $faker){
return [
'id' => $faker->uuid,
'name' => $faker->text,
'description' => $faker->paragraph,
];
});
$factory->afterCreating(Film::class, function(Film $film, Faker $faker) {
$category = Category::where('main-cat', 'Science')->where('sub-cat', 'Fiction')->first();
$language = Languages::where('name', 'english')->first();
$film->categories()->attach($category);
$film->languages()->attach($language);
});
I am trying to cleanup my controller. I have a lot form fields so I want to use observer to insert for the other model that have relationship with the main model
I have already successfully insert the request to the database in a controller but it seems to long and heavy. See code below
function insert(Request $request){
$bankStatementName = time().'.'.request()->bankStatement->getClientOriginalExtension();
request()->bankStatement->move(public_path('bankStatement'), $bankStatementName);
$identityName = time().'.'.request()->identity->getClientOriginalExtension();
request()->identity->move(public_path('identity'), $identityName);
$passportName = time().'.'.request()->passport->getClientOriginalExtension();
request()->passport->move(public_path('passport'), $passportName);
$customer = Customer::find(Auth::user()->id);
$relations = new Customer_relationship([
'kinName' => $request->kinName,
'kinGender' => $request->kinGender,
'kinEmail' => $request->kinEmail,
'kinRelation' => $request->kinRelation,
'kinAddress' => $request->kinAddress
]);
$company = new Customer_company([
'compName' => $request->compName,
'compEmail' => $request->compEmail,
'compPhone' => $request->compPhone,
'compAddress' => $request->compAddress
]);
$bank = new Customer_bank([
'accNumber' => $request->accNumber,
'bankName' => $request->bankName,
'accName' => $request->accName
]);
$document = new Customer_document([
'identity' => $identityName,
'bankStatement' => $bankStatementName,
'passport' => $passportName
]);
$customer->relation()->save($relations);
$customer->company()->save($company);
$customer->bank()->save($bank);
$customer->document()->save($document);
Customer::where('user_id', Auth::user()->id)
->update([
'title' => $request->title,
'middlename' => isset($request->middlename) ? $request->middlename : "",
'phone' => $request->phone,
'gender' => $request->gender,
'DOB' => $request->DOB,
'marital' => $request->marital,
'residential_address' => $request->residential_address,
'city' => $request->city,
'state' => $request->state,
'lga' => $request->lga,
'nationality' => $request->nationality,
'complete_registration' => 1 ]);
}
So how can I access the form request field from Updating function from observer to do a controller cleanup
Welcome to SO!
If you want to use Observers here, you should start by reading up on https://laravel.com/docs/5.8/eloquent#observers and https://laravel.com/docs/5.8/queues
This will likely work if you have all the data needed on your parent model, since you would just pass that model into the job that was triggered by the observer. If not, then observer/job might not be the best solution in your case. Instead I would probably create some sort of service, where you move the responsibility for creating these relationships. That way you can keep a clean controller level that only calls a service to create the models and then returns the result.
An example of this could be:
namespace App\Http\Controllers;
use App\Models\Something\SomeService;
class SomeController extends Controller
{
/**
* #var SomeService
*/
private $someService;
public function __construct(SomeService $someService)
{
$this->someService = $someService;
}
public function store()
{
$request = request();
$name = $request->input('name');
$something = $this->someService->create($name);
return response()->json(['data' => $something]);
}
}
namespace App\Models\Something;
class SomeService
{
public function create(string $name): Something
{
// Do whatever in here...
}
}
This is a simplified example of how I would do it. Hope it helps you a bit.
If you still want to use a job to take care of this, then I still don't think an observer is the right solution for you, as those are triggered on model events, such as created. This mean that you will not have access to the request object at that time, but only was was created (The model). Instead you could dispatch a job directly from the controller/service. That is all described in the queue link I posted at the top of the answer.
I have a working api only application.
I am required to write a test decided to use laravel's phpunit test. This simple app allows only authenticated users can store, update or delete a book. Everyone else (authenticated or not) can retrieve a list of all books or view details of one book.
For my books test, I have written a test that first creates a user then a random token for the user. Then the token is passed using withHeaders when posting a new book record
class BooksTest extends TestCase
{
public function test_onlyAuthenticatedUserCanAddBookSuccessfully()
{
$user = factory(User::class)->create();
$token = str_random(10);
$book = factory(Book::class)->create();
$response = $this->withHeaders(['Authorization' => "Bearer $token"])
->json('POST', '/api/books', [
'title' => 'book post',
'author' => 'post author'
]);
$response->assertStatus(201);
}
}
Here I am using the default Laravel 5.6 UserFactory and my own BookFactory
$factory->define(Book::class, function (Faker $faker) {
return [
'title' => $faker->sentence,
'author' => $faker->name,
'user_id' => 1
];
});
$factory->define(Rating::class, function (Faker $faker) {
return [
'user_id' => 1,
'book_id' => mt_rand(1, 2),
'rating' => mt_rand(1, 5)
];
});
When I run the test, it fails and I get 401 instead of 200 which means the user is unauthorized.
I have a feeling that I have probably not set the $user in my test properly to be used during POST but I am not sure and really need help to get it right.
you can send headers in the fourth params of json() method as
$response = $this->json('POST', '/api/books', [
'title' => 'book post',
'author' => 'post author'
],['Authorization' => "Bearer $token"]);
since json method itself has provision to pass headers
or you can use post() method as
$response = $this->post('/api/books', [
'title' => 'book post',
'author' => 'post author'
],['Authorization' => "Bearer $token"]);
Try this instead hope this solves your issues
Not sure how authentication is hooked on your application, but you could try this:
...
$this->actingAs($user)
->jsonPost('/api/books', [
// ...
]);
$response->assertStatus(201);
For the following factory definition, the column order needs to be sequential. There is already a column id that is auto-incremented. The first row's order should start at 1 and each additional row's order should be the next number (1,2,3, etc.)
$factory->define(App\AliasCommand::class, function (Faker\Generator $faker) {
return [
'user_id' => App\User::inRandomOrder()->first()->id,
'command' => $faker->word,
'content' => $faker->sentence,
'order' => (App\AliasCommand::count()) ?
App\AliasCommand::orderBy('order', 'desc')->first()->order + 1 : 1
];
});
It should be setting the order column to be 1 more than the previous row, however, it results in all rows being assigned 1.
Here's something that might work.
$factory->define(App\AliasCommand::class, function (Faker\Generator $faker) {
static $order = 1;
return [
'user_id' => App\User::inRandomOrder()->first()->id,
'command' => $faker->word,
'content' => $faker->sentence,
'order' => $order++
];
});
It just keeps a counter internal to that function.
Update:
Laravel 8 introduced new factory classes so this request becomes:
class AliasCommandFactory extends Factory {
private static $order = 1;
protected $model = AliasCommand::class;
public function definition() {
$faker = $this->faker;
return [
'user_id' => User::inRandomOrder()->first()->id,
'command' => $faker->word,
'content' => $faker->sentence,
'order' => self::$order++
];
}
}
The answer by #apokryfos is a good solution if you're sure the factory model generations will only be run in sequential order and you're not concerned with pre-existing data.
However, this can result in incorrect order values if, for example, you want to generate models to be inserted into your test database, where some records already exist.
Using a closure for the column value, we can better automate the sequential order.
$factory->define(App\AliasCommand::class, function (Faker\Generator $faker) {
return [
'user_id' => App\User::inRandomOrder()->first()->id,
'command' => $faker->word,
'content' => $faker->sentence,
'order' => function() {
$max = App\AliasCommand::max('order'); // returns 0 if no records exist.
return $max+1;
}
];
});
You almost had it right in your example, the problem is that you were running the order value execution at the time of defining the factory rather than the above code, which executes at the time the individual model is generated.
By the same principle, you should also enclose the user_id code in a closure, otherwise all of your factory generated models will have the same user ID.
To achieve true autoIncrement rather use this approach:
$__count = App\AliasCommand::count();
$__lastid = $__count ? App\AliasCommand::orderBy('order', 'desc')->first()->id : 0 ;
$factory->define(App\AliasCommand::class,
function(Faker\Generator $faker) use($__lastid){
return [
'user_id' => App\User::inRandomOrder()->first()->id,
'command' => $faker->word,
'content' => $faker->sentence,
'order' => $faker->unique()->numberBetween($min=$__lastid+1, $max=$__lastid+25),
/* +25 (for example here) is the number of records you want to insert
per run.
You can set this value in a config file and get it from there
for both Seeder and Factory ( i.e here ).
*/
];
});
In Laravel 9 (and possibly some earlier versions?), there's a pretty clean way to make this happen when you're creating models (from the docs):
$users = User::factory()
->count(10)
->sequence(fn ($sequence) => ['order' => $sequence->index])
->create();
If you'd like to start with 1 instead of 0:
$users = User::factory()
->count(10)
->sequence(fn ($sequence) => ['order' => $sequence->index + 1])
->create();
The solution also solves already data on table conditions:
class UserFactory extends Factory
{
/**
* #var string
*/
protected $model = User::class;
/**
* #var int
*/
protected static int $id = 0;
/**
* #return array
*/
public function definition()
{
if ( self::$id == 0 ) {
self::$id = User::query()->max("id") ?? 0;
// Initialize the id from database if exists.
// If conditions is necessary otherwise it would return same max id.
}
self::$id++;
return [
"id" => self::$id,
"email" => $this->faker->email,
];
}
}
In laravel 4, I used the sometimes() method as below:
$validator = \Validator::make(
\Input::all(),
array(
'name' => array('required'),
'recurrence' => array('required_if:recurring,on'),
)
);
$validator->sometimes('recurrence', 'integer|min:1', function($input) {
return $input->recurring == 'on';
});
Notice integer|min:1 are applied to recurring only if recurrence is presented.
In laravel 5, I tried to implement the validation as a request class:
class CreateProductRequest extends Request {
public function authorize(){
return true;
}
public function rules(){
return [
'name' => array('required'),
'recurrence' => array('required_if:recurring,on'),
];
}
}
Looks like from a request class I am unable to call sometimes() method. The idea is to avoid validation code at controller.
Ok, I have emulated the behaviour expected using a custom condition without be 100% sure weather is the best practice:
$rules = [
'name' => array('required'),
'recurrence' => array('required_if:recurring,on'),
];
if ($this->has('recurring')){
$rules['recurrence'] = $rules['recurrence'] + ['integer', 'min:1'];
}
return $rules;