rspec - How to test a rails PORO called from controller -


i have extracted part of foos controller new rails model perform action:

foos_controller.rb

class fooscontroller < applicationcontroller    respond_to :js    def create     @foo = current_user.do_something(@bar)     actioned_bar = actionedbar.new(@bar)     actioned_bar.create     respond_with @bar   end 

actioned_bar.rb

class actionedbar   def initialize(bar)     @bar = bar   end    def create     if @bar.check?       #     end   end end 

i got working first i'm trying back-fill rspec controller tests.

i'll testing various model methods , doing feature test make sure it's ok point of view add test make sure new actioned_bar model called foos controller @bar.

i know in rspec can test receives with arguments i'm struggling work.

    "calls actionedbar.new(bar)"       bar = create(:bar)       expect(actionedbar).to receive(:new)        xhr :post, :create, bar_id: bar.id     end 

this doesn't work though, console reports:

nomethoderror:    undefined method `create' nil:nilclass 

which strange because when use expect(actionedbar).to receive(:new), rest of controller tests work fine.

if try do:

    "calls actionedbar.new(bar)"       bar = create(:bar)       actioned_bar = actionedbar.new(bar)       expect(actioned_bar).to receive(:create).with(no_args)        xhr :post, :create, bar_id: bar.id     end 

the console says:

(#<actionedbar:0xc8f9f74>).create(no args)        expected: 1 time no arguments        received: 0 times no arguments 

if put in controller whilst running test; reason test causes actioned_bar in controller output nil fine other controller tests.

is there way can test actionedbar being called in controller spec?

you can use expect_any_instance_of(actionedbar).to receive(:create), because instance in spec , in controller different instances.

if want use original object, can use expect(actionedbar).to receive(:new).and_call_original (without #new return nil , you'll nomethoderror).


Comments

Popular posts from this blog

java - nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet Hibernate+SpringMVC -

sql - Postgresql tables exists, but getting "relation does not exist" when querying -

asp.net mvc - breakpoint on javascript in CSHTML? -