
Add MySQL Functions to SQLite in Laravel Tests
Originally published at recca0120.github.io When running tests with SQLite, MySQL-specific functions like FIELD throw a no such function error. Why It Fails Each database has different built-in functions. SQLite doesn't have MySQL's FIELD function. Suppose your code has this query: Route :: get ( '/' , function () { return User :: query () -> orderByRaw ( 'FIELD(id, 3, 5, 4, 1, 2)' ) -> get (); }); It works fine with MySQL, but tests using SQLite will fail: namespace Tests\Feature ; use App\Models\User ; use Illuminate\Foundation\Testing\RefreshDatabase ; use Tests\TestCase ; class ExampleTest extends TestCase { use RefreshDatabase ; public function test_sql_function (): void { User :: factory () -> count ( 5 ) -> create (); $data = $this -> get ( '/' ) -> assertStatus ( 200 ) -> collect (); self :: assertEquals ([ 3 , 5 , 4 , 1 , 2 ], $data -> pluck ( 'id' ) -> toArray ()); } } Add It with sqliteCreateFunction PHP's SQLite PDO supports custom functions. Just add it in TestCase 's setU
Continue reading on Dev.to
Opens in a new tab


