How do you know for sure that the created Author instance has id = 1?
$book = factory(Book::class)->make([
'author_id' => $author->id,
'title' => 'THis iS tHe titlE'
]);
I have a test that I can't get to pass due to a validation error.
I have this in my store method
public function store(Request $request)
{
$request->validate([
'author_id' => 'required|exists:authors, id',
'title' => 'required'
]);
$book = new Book();
$book->author_id = $request->author_id;
$book->title = $request->title;
$book->series = $request->series;
$book->part = $request->part;
$book->format_id = $request->format_id;
$book->genre_id = $request->genre_id;
$book->isbn = $request->isbn;
$book->released = $request->released;
$book->reprinted = $request->reprinted;
$book->pages = $request->pages;
$book->blurb = $request->blurb;
$book->save();
}
And I'm adding validations one by one. However when running this test.
/** @test */
public function the_title_must_start_every_word_with_an_upper_case()
{
$author = factory(Author::class)->create();
$book = factory(Book::class)->make([
'title' => 'THis iS tHe titlE'
]);
$response = $this->post('/books', $book->toArray());
$this->assertEquals(1, Book::where('title', 'This Is The Title')->count());
}
It fails because of the an invalid author_id. A ddof the sessions errors gives me this
Illuminate\Support\ViewErrorBag {#714
#bags: array:1 [
"default" => Illuminate\Support\MessageBag {#715
#messages: array:1 [
"author_id" => array:1 [
0 => "The selected author id is invalid."
]
]
#format: ":message"
}
]
}
Even if I assign the `$author->id in my test it fails.
Using this factory to create the book.
$factory->define(App\Book::class, function (Faker $faker) {
return [
'author_id' => 1,
'format_id' => 1,
'genre_id' => 1,
'title' => 'Some Fake Title',
'series' => 'Some Fake Serie',
'part' => 9999,
'isbn' => '0123456789',
'released' => 1900,
'reprinted' => 3000,
'pages' => 100,
'blurb' => 'Some nice fake text about the book'
];
});
and this in my AuthorFactory.
<?php
use Faker\Generator as Faker;
$factory->define(App\Author::class, function (Faker $faker) {
return [
'first_name' => $faker->firstName(),
'last_name' => $faker->lastName()
];
});
My happy path test also fails after adding this validation
'author_id => 'required|exists:authors, id
Probably a simple error but I can't see it.
Can you remove the space before id in the validation rule?
Aside I don't like using a factory as a data provider for simulating a request; your model probably has more properties than the form you are testing has fields.
I prefer to have a private method in my test which simulates a valid form, but allow overrides to test specific functionality such as validation rules.
Please or to participate in this conversation.