Laravel testing with failing foreign key check on sqlite

as a firm believer in Test Driven Development (TDD), I make sure to test all of my codes. Whenever I am coding in PHP using laravel, I opt to use sqlite memory as my testing database because of the speed it gives and it is very inexpensive. Hwoever, sqlite has some shortcomings, one of which is its default lack of foreign keys. This may prove to be problematic when you are testing relationships in your models and you wish to enforce refential inetgrity..

To enable the use of foreign keys in sqlite, use the code below

add the code below into the boot method of  your AppServiceProvider.php

if (\DB::connection() instanceof \Illuminate\Database\SQLiteConnection) {
  \DB::statement(\DB::raw('PRAGMA foreign_keys=1'));

Quick primer- How to evaluate strings to boolean in PHP

Occasionally in PHP, you need to evaluate a string value to its boolean counterpart. One very common example of when this is needed is when you try to represent boolean in query string parameters. The jury is still out on the most appropriate way to represent a boolean value in Rest API or a query string, some of the

  1. true
  2. True
  3. TRUE
  4. false
  5. FALSE
  6. Yes
  7. No
  8. On
  9. Off
  10. 0
  11. 1

all of the values listed above are valid ways to represent a boolean value in your API or query string hence the need find a valid way to change the values correctly to their boolean value.

Evaluation using filter_var()

this filter_var method has been present in PHP since php5 and as the name implies, it filters a variable with a specified filter, for the purpose of this writeup, we are interested only in the boolean filter which is named FILTER_VALIDATE_BOOLEAN.

check the example below

filter_var("1", FILTER_VALIDATE_BOOLEAN)   // => bool(true)
filter_var("on", FILTER_VALIDATE_BOOLEAN)  // => bool(true)
filter_var("false", FILTER_VALIDATE_BOOLEAN) // => bool(false)

Value (int) BoolVal Boolean
1 1 TRUE
 0 0 FALSE
true 1 TRUE
false 0 FALSE
1 1 TRUE
1 1 TRUE
on 1 TRUE
off 0 FALSE
yes 1 TRUE
no 0 FALSE
True 1 TRUE