Search code examples
ruby-on-railsrubyfactory-botmachinistfactories

Is there any rails factory to help me test non persistant models?


I'm working on a rails application on which the models are plain ruby classes without any persistence layer (no active record or similar). I want to test these models from RSpec with all the niceties that some factories provide (machinist, factory-girl). These models may get associations with persistent models in the future or may implement a custom persistance model.

Any suggestions?


Solution

  • I like to use the Sham gem. As long as you have a non-persistent model that conforms to some basic implementation details you should be fine. For instance, in my Rails app I would do the following:

    # sham/dog_sham.rb
    class Dog::Sham
      def self.options
        { name: "Barney" }
      end
    end
    
    # app/models/dog.rb
    class Dog < Struct.new(:name)
      def self.create options
        self.new(options[:name])
      end
    end
    

    Then in the console I can create a factory Dog using the sham command:

    Sham::Config.activate!
    Dog.sham!
    => #<struct Dog name="Barney">