Create a gist now

Instantly share code, notes, and snippets.

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