简体   繁体   中英

Machinist for Non-ActiveRecord Models

Is it possible to use Machinist to create blueprints for non-activerecord models? Seems to generate an error no matter what I try!

If this is impossible with Machinist, is there another fixture generating gem that can do it? I've also read that Factory Girl has issues with this.

I did a little bit of investigating into Machinist 2 beta 1 and it looks like it supports plain ruby objects. Here's what I did to get it working. Happy to learn of any simpler solutions.

require 'rubygems'
require 'machinist'
require 'faker'

class YourObject
 attr_accessor :field1, :field2
end


# For all Objects
class Object
 extend Machinist::Machinable

 def self.blueprint_class
   Machinist::Blueprint
 end
end   

# Or just one object
YourObject.send(:extend, Machinist::Machinable)
YourObject.class_eval do
 def self.blueprint_class
   Machinist::Blueprint
 end
end



YourObject.blueprint do
 field1 { rand(1000) }
 field2 { Faker::Name }
end

obj = YourObject.make

In case anyone's curious, one of the problems (there may be others) with FactoryGirl and POROs is that it doesn't handle constructors with arguments. You can make due per the answer here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM