Search code examples
phpspec

testing output buffering with phpspec


Given the following PHPUnit code, how do I translate this to a phpspec test?

$content = 'Hello world!';
ob_start();
$this->displayer->output($content);
$output = ob_get_clean();
$this->assertEquals($content, $output);

What $this->displayer->output($content) does is simply echo the $content:

class Displayer {
    public function display(string $content) { echo $content; }
}

Solution

  • I believe this is the only way:

    use PHPUnit\Framework\Assert;
    
    public function it_outputs_a_string()
    {
        $content = 'Hello world!';
        ob_start();      
        $this->display($content);
        $output = ob_get_clean();
    
        Assert::assertEquals($content, $output);
    }