I'm attempting to test relationships between models using Ardent
and FactoryMuff
. I'm able to test the relationship in the belongs_to
direction, but I'm having trouble testing it in the has_many
direction.
The models I'm testing are a residential real estate rental application and it's corresponding rental history. A very simplified db schema:
+--------------+
| applications |
+--------------+
| id |
| name |
| birthday |
| income |
+--------------+
+----------------+
| history |
+----------------+
| id |
| application_id |
| address |
| rent |
+----------------+
This is my history model:
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');
}
}
This is my test to make sure that a history object belongs to a rental 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);
}
}
This works just fine. However, I can't figure out how to test the relationship in the other direction. In the project requirements, a rental application MUST have at least one rental history object associated with it. This is my application model:
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;
}
}
This is how I'm attempting to test the has_many
relationship:
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);
}
}
This results in ErrorException: Undefined property: Illuminate\Database\Eloquent\Collection::$application_id
when I run my unit tests. It makes sense to me. Nowhere have I told FactoryMuff
to create at least one corresponding History
object to go along with my Application
object. Nor have I written any code to enforce the requirement that an Application
object must have at least one History
object.
Questions
- How do I enforce the rule "an
application
object MUST have at least onehistory
object"? - How do I test the
has_many
direction of the relationship?