开发者

Can you write stubs/mocks/doubles for methods inside of a method call?

开发者 https://www.devze.com 2023-03-12 22:36 出处:网络
My method looks like: def some_method(....) user = User.where(\"....\").first if !user.nil? if .. user.d开发者_运维知识库elete

My method looks like:

def some_method(....)

  user = User.where("....").first

  if !user.nil?

     if ..
         user.d开发者_运维知识库elete
     elsif
         user.update_attributes(...)

  else
     new_user = User.new(...)
     new_user.save!
  end

end

As you can see both user and new_user are instantiated inside this method.

Is it possible to stub and mock (expectations) for these objects when I am testing the method?

I am trying this:

it "should ...." do

  d = double("user double")
  d.should_receive(:save!).once

  res = User.some_method(....)

end

But I get an error saying expected 1 time and received 0 times.

Am I doing this right? (obviously not, is this possible to test for since I can't pass these stubs/mocks to the method being tested)


You can do something like this:

user_double = double("user")
User.should_receive(:where).and_return(user_double)
user_double.should_receive(:delete)
0

精彩评论

暂无评论...
验证码 换一张
取 消