Using Crypt With Laravel Phpunit Tests

- 1 answer

I am using phpunit with Laravel to perform some tests. I have a lot of database data that is encrypted.

In one of my tests I fill out a form, and once it is completed, the data is encrypted using Crypt::encrypt('data from field goes here').

Here is the code:

             ->type('FirstNameTest1', 'first_name')
             ->press('Create Request')
             ->see('The request has been created.');

// Fails here
$this->seeInDatabase('requests', ['first_name' => Crypt::encrypt('FirstNameTest1')]);

I get the following error message:

Unable to find row in database table [requests] that matched attributes [{"first_name":"eyJpdiI6InFWbGJmSU9rR0NHMjFnMjR4QVVyalE9PSIsInZhbHVlIjoiaDBMcGNxYzdsRlhjNDd3M2E5OGxQbUVkaHhzdEpIOERDcytwQytzZUN4MD0iLCJtYWMiOiJlN2U2MzczYTlhMDgyYTMxOWJmMGQyZDU0MzFiMmZiZjhkMDM1ZjA2YWFhZGVkYTZhMGRkNGMzNDY0ZTAzMjZmIn0="}].

I tried to manually check to see if the record existed after being created and it did not show up. I remember reading something about data not persisting when running tests, so that would make sense... But are you able to think of any reasons why it wouldn't be able to find that record during the test?



The Crypt::encrypt() functionality does not create a reproducible hash. This is why you're not able to find the record, because the hash stored in the database will be different than the second hash you're looking for.

For example, below is the output from a php artisan tinker session:

>>> Illuminate\Support\Facades\Crypt::encrypt('hello');
>>> Illuminate\Support\Facades\Crypt::encrypt('hello');

As you can see, the Crypt::encrypt() function run twice in a row for the same text produced different hashes.

You will need to find a different assertion for your test, such as retrieving the record from the database and checking if Crypt::decrypt($first_name) == 'FirstNameTest1'.