1

I am running a unit test to check that

  1. View page exists
  2. AssertSee that text appears on the page and with a string limit

I am getting an invalid argument exception:

1) Tests\Feature\ViewAllPostTest::testCanViewAllPosts
InvalidArgumentException: You requested 1 items, but there are only 0 items available.

C:\projects\car-torque-laravel\vendor\laravel\framework\src\Illuminate\Support\Arr.php:472
C:\projects\car-torque-laravel\vendor\laravel\framework\src\Illuminate\Support\Collection.php:1486
C:\projects\car-torque-laravel\database\factories\PostFactory.php:12
C:\projects\car-torque-laravel\vendor\laravel\framework\src\Illuminate\Database\Eloquent\FactoryBuilder.php:274
C:\projects\car-torque-laravel\vendor\laravel\framework\src\Illuminate\Database\Eloquent\FactoryBuilder.php:292
C:\projects\car-torque-laravel\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Concerns\GuardsAttributes.php:122
C:\projects\car-torque-laravel\vendor\laravel\framework\src\Illuminate\Database\Eloquent\FactoryBuilder.php:300
C:\projects\car-torque-laravel\vendor\laravel\framework\src\Illuminate\Database\Eloquent\FactoryBuilder.php:219
C:\projects\car-torque-laravel\vendor\laravel\framework\src\Illuminate\Database\Eloquent\FactoryBuilder.php:178
C:\projects\car-torque-laravel\tests\Feature\ViewAllPostTest.php:19

My source code is as follows:

Test Function

namespace Tests\Feature;

use App\Post;
use Tests\TestCase;

class ViewAllPostTest extends TestCase
{

    /**
     * @group posts
     *
     * @return void
     */
    public function testCanViewAllPosts()
    {
        //arrange
        $post = factory(Post::class)->create();

        //action
        $response = $this->get('/posts');

        //assert
        $response->assertStatus(200);
        $response->assertSee($post->body);
        $response->assertSee(str_limit($post->body));

    }
}

Factory Class

use App\Post;
use App\User;
use Faker\Generator as Faker;

$factory->define(Post::class, function (Faker $faker) {
    return [
        'body' => $faker->text,
        'user_id' => User::all()->random()->id,
        'created_at' => now(),
        'updated_at' => now(),
    ];
});

1 Answer 1

2

'user_id' => User::all()->random()->id,

In the above line of your factory, you want random id form your users table. But have you created any User before running the test. At least a user should be created before creating post using post factory.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your input much appreciated Imran

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.