Skip to content

Instantly share code, notes, and snippets.

@rjz
Last active December 12, 2015 06:49
Show Gist options
  • Select an option

  • Save rjz/4732358 to your computer and use it in GitHub Desktop.

Select an option

Save rjz/4732358 to your computer and use it in GitHub Desktop.
# `factory` implements test fixtures as object factories.
factory = (fixture) ->
defaults = if _.isFunction(fixture) then fixture() else fixture
(klass, attrs) ->
if _.isFunction(klass) # build it
new klass(_.extend {}, defaults, attrs)
elseif _.isObject(klass) # no klass, just attrs
_.extend {}, defaults, klass
else #
defaults

Using the factory

Given a fixture defined like so:

FooFixture = factory ->
  id: 13
  foo: 'bar'

the factory may be used to retrieve the raw fixture:

attributes = FooFixture()
model = new MyModel(attributes)

or to pass the fixture as a constructor argument:

model = new FooFixture(MyModel) # equivalent to above

Overriding the fixture

attributes = FooFixture(id: 42)
model = new MyModel(attributes)    

model = new FooFixture(MyModel, id: 42) # override ID
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment