【发布时间】:2014-01-04 12:16:46
【问题描述】:
我正在尝试使用Ardent 和FactoryMuff 来test relationships between models。我可以在belongs_to 方向测试关系,但在has_many 方向测试它时遇到问题。
我正在测试的模型是住宅房地产租赁应用程序及其相应的租赁历史记录。一个非常简化的数据库架构:
+--------------+
| applications |
+--------------+
| id |
| name |
| birthday |
| income |
+--------------+
+----------------+
| history |
+----------------+
| id |
| application_id |
| address |
| rent |
+----------------+
这是我的历史模型:
class History extends Ardent
{
protected $table = 'history';
public static $factory = array(
'application_id' => 'factory|Application',
'address' => 'string',
'rent' => 'string',
);
public function application()
{
return $this->belongsTo('Application');
}
}
这是我的测试,以确保历史对象属于租赁应用程序:
class HistoryTest extends TestCase
{
public function testRelationWithApplication()
{
// create a test rental history object
$history = FactoryMuff::create('History');
// make sure the foreign key matches the primary key
$this->assertEquals($history->application_id, $history->application->id);
}
}
这很好用。但是,我不知道如何测试另一个方向的关系。在项目要求中,租赁应用必须至少有一个与之关联的租赁历史对象。这是我的应用模型:
class Application extends Ardent
{
public static $rules = array(
'name' => 'string',
'birthday' => 'call|makeDate',
'income' => 'string',
);
public function history()
{
return $this->hasMany('History');
}
public static function makeDate()
{
$faker = \Faker\Factory::create();
return $faker->date;
}
}
这就是我尝试测试has_many 关系的方式:
class ApplicationTest extends TestCase
{
public function testRelationWithHistory()
{
// create a test rental application object
$application = FactoryMuff::create('Application');
// make sure the foreign key matches the primary key
$this->assertEquals($application->id, $application->history->application_id);
}
}
当我运行单元测试时,这会导致ErrorException: Undefined property: Illuminate\Database\Eloquent\Collection::$application_id
。对于我,这说得通。我没有告诉FactoryMuff 至少创建一个对应的History 对象与我的Application 对象一起使用。我也没有编写任何代码来强制要求 Application 对象必须至少有一个 History 对象。
问题
- 如何执行“
application对象必须至少有一个history对象”规则? - 如何测试
has_many关系的方向?
【问题讨论】:
标签: php unit-testing laravel phpunit ardent