Sorry for the delay. I have a deadline to finish writing an article so I've been busy with that. Just taking 10 minutes out to chip into this thread again for a moment
First things first, you've got the right idea with the tearDown() method removing a previously created file! However, I think we'll avoid creating a file with a fixed name each time. I had envisaged that if the file does not exist and save() is called the ArrayStorageModel will try to create the file before saving the data. As a result, I think this is more flexible:
Code: Select all
class ArrayStorageModelTest extends UnitTestCase {
public function setUp() {
foreach (glob(TEST_TMP . '/*.*') as $file) {
unlink($file);
}
}
public function testSomething(){
$this->_createTestfile('test.php', '<?php $x = array("foo" => "bar"); ?>');
$model = $this->_createStorageModel('test.php', 'x');
//Make some assertions here
}
private function _createStorageModel($filename, $arrayName) {
return new ArrayStorageModel(TEST_TMP . '/' . $filename, $arrayName);
}
private function _createTestFile($filename, $contents) {
file_put_contents(TEST_TMP . '/' . $filename, $contents);
}
}
NOTE that I also defined a new constant in configure.php for re-use later.
The alternative to doing this is to use the tmp directory only for writing data and to provide some real files for loading. I prefer the approach we're going with however because it's a lot easier to read the tests.
Ok, here's our first test?
Code: Select all
<?php
require_once dirname(__FILE__) . '/../configure.php';
require_once CLASS_BASE . '/ArrayStorageModel.php';
class ArrayStorageModelTest extends UnitTestCase {
public function setUp() {
foreach (glob(TEST_TMP . '/*.*') as $file) {
unlink($file);
}
}
public function testSimpleArrayCanBeLoadedFromFile() {
$this->_createTestFile('test.php', '<?php $data = array("foo" => "bar"); ?>');
$this->assertEqual(
array("foo" => "bar"), $this->_createStorageModel('test.php', 'data')->load(),
'%s: Array loaded from StorageModel should match the array in the file'
);
}
// -- Helpers
private function _createStorageModel($filename, $arrayName) {
return new ArrayStorageModel(TEST_TMP . '/' . $filename, $arrayName);
}
private function _createTestFile($filename, $contents) {
file_put_contents(TEST_TMP . '/' . $filename, $contents);
}
}
Files attached.
Go ahead an provide an implementation
This test is going to be incredibly short
