Skip to content

Instantly share code, notes, and snippets.

@tylerhunt
Last active August 29, 2015 13:56
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save tylerhunt/9255194 to your computer and use it in GitHub Desktop.
An example showing how to use factory_girl without polluting the global scope.
require 'factory_girl'
class Simulator
def initialize(model, options={}, &block)
self.model = model
self.strategy = options.fetch(:strategy) { FactoryGirl::Strategy::Build }
self.factory = define(&block)
end
def build(overrides={}, &block)
factory.run(strategy, overrides, &block)
end
private
attr_accessor :model
attr_accessor :strategy
attr_accessor :factory
def define(&block)
FactoryGirl::Factory.new(model).tap do |factory|
proxy = FactoryGirl::DefinitionProxy.new(factory.definition)
proxy.instance_eval &block
end
end
end
require 'simulator'
require 'virtus'
describe Simulator do
let(:model) {
Class.new do
include Virtus.model
attribute :value, Integer
end
}
let(:simulator) {
Simulator.new(model) do
value { 42 }
end
}
describe '#build' do
it 'returns an instance of the model' do
expect(simulator.build).to be_a model
end
it 'uses the factory definition' do
instance = simulator.build
expect(instance.value).to eq 42
end
it 'allow values to be overridden' do
instance = simulator.build(value: 37)
expect(instance.value).to eq 37
end
it 'yields the model' do
expect { |block| simulator.build({}, &block) }
.to yield_with_args an_instance_of(model)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment