ruby on rails - Rspec can't stub where or find_by_, only find -


i'm going share several pairs of run code , test code. basically, test code working when use find on object class, problem find 1 method don't want use because i'm not looking primary key!

approach 1: stubbing :where plan.all first can called on it

#run code @current_plan = plan.where(stripe_subscription_id: event.data.object.lines.data.first.id).first  #test code @plan = plan.new #so first plan i'd find plan.stub(:where).and_return(plan.all)  #result of @current_plan (expecting @plan) => nil 

approach 2: chain stubbing :where , :first

#run code @current_plan = plan.where(stripe_subscription_id: event.data.object.lines.data.first.id).first  #test code @plan = plan.new #so first plan i'd find plan.stub_chain(:where, :first).and_return(@plan)  #result of @current_plan (expecting @plan) => nil 

approach 3: stubbing custom :find_by

#run code @current_plan = plan.find_by_stripe_subscription_id(event.data.object.lines.data.first.id)  #test code @plan = plan.new plan.stub(:find_by_stripe_subscription_id).and_return(@plan)  #result of @current_plan (expecting @plan) => nil 

approach 4: stubbing :find works! can't find primary key... ideally need approach 3 work...

#run code @current_plan = plan.find(2) #for giggles, make sure stub ignoring 2 argument  #test code @plan = plan.new plan.stub(:find).and_return(@plan)  #result of @current_plan (expecting @plan) => @plan 

i guess answer how can creatively use :find arguments, though understand isn't best practice...

you can stub methods. these tests pass:

require 'rails_helper'  rspec.describe foo, type: :model   let(:foo) { double(name: "foo") }    "works find"     expect(foo).to receive(:find).and_return(foo)     expect(foo.find(1)).to eq foo    end    "works find_by"     expect(foo).to receive(:find_by_name).and_return(foo)     expect(foo.find_by_name("foo")).to eq foo   end    "works where"     expect(foo).to receive(:where).and_return([ foo ])     expect(foo.where(name: "foo")).to eq [foo]   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? -