ruby on rails - factory girl passing arguments to model definition on build/create -
models/message.rb
class message attr_reader :bundle_id, :order_id, :order_number, :event def initialize(message) hash = message @bundle_id = hash[:payload][:bundle_id] @order_id = hash[:payload][:order_id] @order_number = hash[:payload][:order_number] @event = hash[:concern] end end
spec/models/message_spec.rb
require 'spec_helper' describe message 'should save payload' payload = {:payload=>{:order_id=>138251, :order_number=>"aw116554416"}, :concern=>"order_create"} message = factorygirl.build(:message, {:payload=>{:order_id=>138251, :order_number=>"aw116554416"}, :concern=>"order_create"}) message.event.should == "order_create" end end
error_log
failures:
1) message should save payload
failure/error: message = factorygirl.build(:message, {:payload=>{:order_id=>138251, :order_number=>"aw116554416"}, :concern=>"order_create"}) argumenterror: wrong number of arguments (0 1) # ./app/models/message.rb:4:in `initialize' # ./spec/models/message_spec.rb:7:in `block (2 levels) in <top (required)>'
factorygirl requires define factory first. let's in file spec/factories/messages.rb:
factorygirl.define factory :message bundle_id 1 order_id 2 ...etc... end end
after you'll able invoke factory build create this:
factorygirl.build(:message) # => bundle_id == 1, order_id == 2 factorygirl.build(:message, order_id: 3) # => bundle_id == 1, order_id == 3
however, there 1 problem in particular case. factorygirl's default builders operate on top of activerecord-alike interface. sets defined attributes through setters, not through hash of attrs passed model constructor:
m = message.new m.bundle_id = 1 m.order_id = 2
so have create custom constructor work interface of model (which doesn't conform activerecord-alike model) , register in factory definition. see factory girl docs details.
let me show example of doing so. sorry didn't test should give clue:
factorygirl.define factory :message ignore # need make attributes transient avoid factorygirl calling setters after object initialization bundle_id 1 order_id 2 end initialize_with new(payload: attributes) end end end
Comments
Post a Comment