ruby on rails - Rspec, can you stub a method that doesn't exist on an object (or mock an object that can take any method)? -


this might sound terribly basic question... let me explain context. i'm retrieving event stripe, purposes of this, works other things i've considered.

the data need in stripe object way buried, i'd have event.data.object.date.lines.first.id. i'm not sure how mock/stub this...

the way can think create fake model simulates stripe event object (in example me, keep in mind stripe events can't user created). , can mock fake model. way it? there way can use rspec stub whole shebang , event.data.object.date.lines.first.id wherever appears should retun 1?

oh , also... if not, , turns out have create fake model... tips appreciated, because right i'm thinking "fake" model needs many layers of children, , totally not worth time investment.

rspec provides no special mechanisms access elements under test, yes, need somehow stub id method , have return whatever wish (e.g. 1).

to that, must have way access event object in test can stub it's data method. once can access it, can use rspec's receive_message_chain matcher specify sequence of methods which, if called, return 1.

if there public strip method can mock return double event, straightforward approach.

if that's not possible, determine class of event , use allow_any_instance_of method stub it's data method. resulting mock follows, assuming foo class of event object you're concerned about:

allow_any_instance_of(foo)).to receive_message_chain(   :data, :object, :date, :lines, :first, :id).and_return(1) 

here's test passes:

module stripe   class event ; end end describe 'stack overflox example'   'should pass'     event = stripe::event.new     expect(event).to receive_message_chain(:data, :object, :date, :lines, :first, :id).and_return(23)     expect(event.data.object.date.lines.first.id).to eq(23)   end end 

Comments

Popular posts from this blog

twig - Using Twigbridge in a Laravel 5.1 Package -

jdbc - Not able to establish database connection in eclipse -

firemonkey - How do I make a beep sound in Android using Delphi and the API? -