Create Transactions Test

27th May 19

I am learning about test driven development and working on building the testing framework before creating the app.

Create a new Feature Test

Firstly you can create a new test easily in laravel:

php artisan make:test CreateTransactionsTest

Within the newly created test file you can a new test method: 

     * A basic feature test example.
     * @test
    public function it_can_create_transactions()

I add the test:

    public function it_can_create_transactions()
        $transaction = make('App\Transaction');
        $this->post('/transactions', $transaction->toArray())


Running the test we get a MethodNotAllowedHttpException: The POST method is not supported for this route. This is because we are missing the route for the post.

Adding the Route

So I add the route in web.php:

Route::post('/transactions', 'TransactionsController@store');

Running the test again you get: BadMethodCallException: Method App\Http\Controllers\TransactionsController::store does not exist. 

So I add the store method in the Transactions controller, run the test again I get: Response status code [200] is not a redirect status code.

 So within the store method I add a redirect.  After running the test again it states that the page fails to create the transaction description.

Creating Transaction

Within the store method I create a Transaction passing the request data array.


Running the test again you get: MassAssignmentException: Add [description] to fillable property to allow mass assignment.  This is because we are using mass assignment by calling request()->all().  We need to define which fields are mass assignable in Transaction model.

public $fillable = ['description'];

Running the test: 

PDOException: SQLSTATE[23000]: Integrity constraint violation: 19 NOT NULL 
constraint failed: transactions.category_id

This is because category_id is not mass assignable.

public $fillable = ['description', 'category_id'];

Now running the test results in a pass.

I have recently completed my apprenticeship.  I am currently building the API to a React JS site using Firebase.