Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

travoltron's avatar

Unit Testing and Redis: enemies of fun

I'm testing a json api, and the methods for creating the test couldn't be easier, however, I'm running into a snag:

Part of the function that I'm testing calls another controller that stashes some data into a redis database, (it's part of a pestering campaign (like a drip campaign, but pushy)). When I use the app normally, everything is gravy, testing in Postman, still gravy.

However, when I start to test, I get some errors about Connection Refused.

Test code:

$faker = Faker::create();
$this->post('/create-user', [
     'email' => $faker->email,
     'password' => $faker->md5
])->seeJson(['uuid']);

And the response:

1) UserTest::testCreate
Unable to find JSON fragment [["uuid"]] within [{"error":{"fields":null,"general":"Connection refused [tcp:\/\/127.0.0.1:6379]"}}].
Failed asserting that false is true.

/if5/vendor/laravel/framework/src/Illuminate/Foundation/Testing/CrawlerTrait.php:261
/if5/vendor/laravel/framework/src/Illuminate/Foundation/Testing/CrawlerTrait.php:220
/if5/tests/UserTest.php:22

The method I'm testing:

$uuid = substr(sha1(microtime()), 0, 12);
$user = new User;
$user->email = Input::get('email');
$user->password = Input::get('password');
$user->uuid = $uuid;
$user->confirmation_token = md5(microtime());
if (!$user->save()) {
    return Response::error('Could not create new user.', $user->getErrors(), 400);
}
$bitfields = BitfieldController::createBitfield($uuid);

The last line is where I get Redis into the mix. How should I proceed with making this test?

Thanks!!

0 likes
8 replies
ohffs's avatar

Maybe show us the bit of code that is causing the problem?

travoltron's avatar
public static function createBitfield($uuid)
{
        // Creating bitfield array for the user
        foreach(config('bitfields') as $bitfield) {
            $bitfields[$bitfield] = false;
        }
        Redis::set('bitfields_'.$uuid, json_encode($bitfields));
        return $bitfields;
}
ohffs's avatar

Is redis running on the same box you're running the test on?

travoltron's avatar

Yep. The typical redis-cli -> ping = PONG definitely in effect.

ohffs's avatar

Is it running on the machine the test site is on? Ie, if you've got a VM with the site is it on there? Quite puzzling...

travoltron's avatar

Yeah, its a homestead box, pretty typical installation.

ohffs's avatar

Are you running your tests inside homestead or on the host machine? Can you ping redis from both? I'm not a homestead user so not 100% what ports it forwards etc...

2 likes
travoltron's avatar
travoltron
OP
Best Answer
Level 2

Yeah, that's what it was, needed to run inside homestead. Closing this and hanging my head in shame....

Please or to participate in this conversation.