johnny's avatar

How would you unit test this helper function

I have a little helper function, and I'd like to write a test for it.

if ( ! function_exists('lang') )
{
    /**
     * Get the translation for the given key or return the default value.
     *
     * @param  string  $key
     * @param  array   $default
     * @return string
     */ 
    function lang($key, $default = null)
    {
        if (Lang::has('system.'.$key)) return Lang::get('system.'.$key);

        return $default;
    }
}

How would your test looks like?

0 likes
5 replies
JohnRivs's avatar

I don't know how it goes when testing a single helper function (I've always tested classes), but if that was a method, in phpspec would look something like:

// app/lang/en/system.php
return array(
    'hello' => 'hi there'
);

// tests
function it_returns_the_key_value_if_exists()
{
    $this->lang('hello', 'world')->shouldReturn('hi there');
}

function it_returns_the_default_if_key_is_not_found()
{
    $this->lang('olleh', 'world')->shouldReturn('world');
}

In the first example, you would pass a key that exists (system.hello). In the second one, you would pass a non existent key.

johnny's avatar

Thank you for your comment @JohnRivs. Yeah, basically that's what I want to do, but I think somehow I should mock the translator class, so if I change

return array(
    'hello' => 'hi there'
);

to

return array(
    'hello' => 'hey there'
);

in the future, this change wouldn't effect my tests. At the moment, if I'd change the language file, I should have change the test as well.

So, this is where I need ideas.

JohnRivs's avatar

I've thought of that too, but I couldn't think of any solution, since you Lang doesn't have something like Lang::put, which would be ideal to use right before the test.

Maybe have a separate lang/en/test.php for now.

MarkRedeman's avatar
Level 10

Since Lang is a facade you can mock it.

I would probably do something like this (note: it might not work out of the box since I haven't tested it):


class LangHelperFunctionTest extends TestCase { /** * @test */ public function it_retrieves_lines() { Lang::shouldReceive('has')->once()->with('system.foo')->andReturn(true); Lang::shouldReceive('get')->once()->with('system.foo')->andReturn("Hello"); $this->assertEquals('Hello', lang('foo', 'World')); } public function it_uses_default_values_when_the_language_service_cant_find_a_translation() { Lang::shouldReceive('has')->once()->with('system.bar')->andReturn(false); $this->assertEquals('Hello World', lang('bar', 'Hello World')); } }
2 likes

Please or to participate in this conversation.