Benedikt
Benedikt

Reputation: 616

How do I create a relationship in ember-cli-mirage?

I'm trying to create Relationships in Ember-Cli-Mirage. Is this possible in a simple way or do I have to use fixtures instead of factories?

These would be my models:

TASK:

export default DS.Model.extend({
  taskName: DS.attr('string'),
  team: DS.hasMany('team', {async: true}),
  taskScore: DS.hasMany('taskScore', {async: true})
});

TEAM:

import DS from 'ember-data';

export default DS.Model.extend({
  teamName: DS.attr('string'),
  task: DS.hasMany('task'),
  taskScore: DS.hasMany('taskScore', {async: true})
});

TASKSCORE:

import DS from 'ember-data';

export default DS.Model.extend({
    score: DS.attr('number'),
    team: DS.belongsTo('team'),
    task: DS.belongsTo('task'),
});

Upvotes: 6

Views: 2065

Answers (1)

Sam Selikoff
Sam Selikoff

Reputation: 12694

Currently you need to assign the ids manually. You could do this in your fixture files, but I prefer to use factories, as they give me a bit more flexibility in my tests.

Define your factories, just assigning the plain attributes:

// app/mirage/factories/task.js
export default Mirage.Factory.extend({
  task_name(i) { return `Task ${i}`; },
});

// app/mirage/factories/team.js
export default Mirage.Factory.extend({
  team_name(i) { return `Task ${i}`; },
});

Then use factory overrides to associate your data in your tests:

// tests/acceptance/some-test.js

test('', function() {
  let task = server.create('task');
  server.createList('team', 5, {task_id: task.id});
});

This creates the related data in your Mirage db. Now if your routes are set up to return associated data, you should be all set.

Upvotes: 6

Related Questions