Created
December 3, 2013 21:54
-
-
Save bendrucker/7778123 to your computer and use it in GitHub Desktop.
Here's how you'd do relatively complex testing the right way. Uses chai-as-promised and mocha-as-promised.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict' | |
expect = require('chai').expect | |
Sinon = require 'sinon' | |
Promise = require 'bluebird' | |
Bookshelf = require '../../lib/db' | |
Model = require '../../lib/model' | |
describe 'Models', -> | |
testTableName = 'model_test' | |
before -> | |
knex = Bookshelf.knex | |
knex.schema.dropTableIfExists(testTableName) | |
.then -> | |
knex.schema.createTable testTableName, (table) -> | |
table.increments() | |
class TestModel extends Model | |
tableName: testTableName | |
initialize: -> | |
Sinon.stub @, 'validate' | |
Sinon.stub @, 'authorize' | |
validate: -> | |
authorize: -> | |
describe 'Inheritance', -> | |
it 'should inherit models from their parent', -> | |
expect(new TestModel).to.be.instanceof TestModel | |
it 'should inherit models through Model', -> | |
expect(new TestModel).to.be.instanceof Model | |
it 'should inherit models from Bookshelf.Model', -> | |
expect(new TestModel).to.be.instanceof Bookshelf.Model | |
describe 'Validation', -> | |
testModel = new TestModel | |
it 'should call a `validate` method upon save if defined', -> | |
testModel.save().finally -> | |
expect(testModel.validate).to.have.been.called | |
it 'should save when validation has run', -> | |
testModel.save() | |
describe 'Saving an invalid model', -> | |
err = new Error name: 'ValidationError' | |
it 'should not save when validation throws an error', -> | |
validationThrowsModel = new TestModel | |
validationThrowsModel.validate.throws(err) | |
expect(validationThrowsModel.save()) | |
.to.be.rejected | |
.then (e) -> | |
expect(e).to.equal err | |
it 'should not save when validation returns a rejected promise', -> | |
validationRejectsModel = new TestModel | |
validationRejectsModel.validate.returns Promise.rejected(err) | |
expect(validationRejectsModel.save()) | |
.to.be.rejected | |
.then (e) -> | |
expect(e).to.equal err |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment