Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create the associated model of fixture if it doesn't exist. #47

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion lib/loader.js
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,11 @@ Loader.prototype.prepFixtureData = function(data, Model) {
promises.push(
(typeof val === 'object' ? assoc.target.find(options) : assoc.target.findOne(options))
.then(function(obj) {
result[assoc.identifier] = obj[assoc.target.primaryKeyField || 'id'];
if (obj) {
result[assoc.identifier] = obj[assoc.target.primaryKeyField || 'id'];
} else {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we add a check here to ensure that on-the-fly association creation is what is intended? Actually this area of code currently has bad error reporting.

I suggest we add a check if the option was specified, if not, it should error and say association not found , such:

throw new Error('No associated model found for: \n\t' + JSON.stringify(options) + '\nwhile processing fixture: \n\t' + JSON.stringify(data));

I'm not positive about the logic to check if your include option was specified, could you add it along with this fallback error case?

result[assoc.options.name.singular] = val;
}
return Promise.resolve();
})
);
Expand Down
25 changes: 25 additions & 0 deletions tests/tests.js
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,31 @@ describe('fixture (with promises)', function() {
});
});

it('should load a fixture and create associated fixture', function() {
return sf.loadFixtures([{
model: 'Foo',
data: {
propA: 'baz',
propB: 2,
bar: {
propA: 'barPropA',
propB: 'barPropB'
}
},
buildOptions: {
include: [models.Bar]
}
}], models).then(function() {
return models.Foo.count();
}).then(function(c){
c.should.equal(1);

return models.Bar.count();
}).then(function(c){
c.should.equal(1);
});
});

it('should not duplicate fixtures whose keys already exist', function() {
return sf.loadFixtures([FOO_FIXTURE, {
model: 'Foo',
Expand Down