とを使用してモデル間の関係をテストしようとしています。関係を方向でテストできますが、方向でテストするのに問題があります。Ardent
FactoryMuff
belongs_to
has_many
私がテストしているモデルは、住宅用不動産賃貸アプリケーションであり、対応する賃貸履歴です。非常に単純化された db スキーマ:
+--------------+
| 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);
}
}
これはうまくいきます。ただし、関係を逆方向にテストする方法がわかりません。プロジェクト要件では、レンタル アプリケーションには少なくとも 1 つのレンタル履歴オブジェクトが関連付けられている必要があります。これは私のアプリケーションモデルです:
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
少なくとも 1 つ作成するように指示したことはありません。また、オブジェクトには少なくとも 1 つのオブジェクトが必要であるという要件を強制するコードも作成していません。History
Application
Application
History
質問
- 「オブジェクトには少なくとも 1 つの
application
オブジェクトが必要です」というルールを適用するにはどうすればよいhistory
ですか? has_many
関係の方向性をテストするにはどうすればよいですか?