Stub class method

62 views
Skip to first unread message

siva

unread,
Jan 7, 2014, 8:41:47 AM1/7/14
to rs...@googlegroups.com


 Hi Everyone

  I am using a model class method on my controller. How can I stub the class method on my controller?

  Thanks
    Siva

Sam Phippen

unread,
Jan 7, 2014, 8:56:27 AM1/7/14
to rs...@googlegroups.com
Hi Siva,

Have you tried

```
allow(MyController).to receive(:method).with(the_arguments_you_expect).and_return(the_return_value_you_expect)
```

you can drop the with, and the and_return as necessary.

Does that answer the question?

Thanks
Sam Phippen

--
You received this message because you are subscribed to the Google Groups "rspec" group.
To unsubscribe from this group and stop receiving emails from it, send an email to rspec+un...@googlegroups.com.
To post to this group, send email to rs...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/rspec/d4246290-e544-421b-b94f-109a0b66801f%40googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.

Alex Chaffee

unread,
Jan 7, 2014, 2:42:42 PM1/7/14
to rs...@googlegroups.com
For a proper stub (canned return value, no validation) I prefer the
simple `stub` block syntax:

```
MyThingy.stub(:method) { |arg| 0 }
```

where 0 is, of course, your stubbed return value and |arg| is optional.

...however, your question is confusing. Is the class method in
question on your model or on your controller?

siva

unread,
Jan 9, 2014, 2:05:09 AM1/9/14
to rs...@googlegroups.com, samph...@googlemail.com

 
    Hi Sam

    You solution is helpful. But actually I have modified your solution as per my need. So I have done like this:

    `````
      Project.accessed_projects(current_resource)  #
    `````

    I have stubbed as below

   
      Project.stub(:accessed_projects).with(current_resource).and_return([FactoryGirl.create(:project)])

      and I used expectation message as

     expect(Project).to have_received(:accessed_projects).with(user.resource)

     Till above it's fine. However if I use 'should_receive' it throws error as

     Project.should_receive(:accessed_projects).with(user.resource) # <Project (class)> expected to have received accessed_projects, but that method has been mocked instead of stubbed

     As per my knowledge both expectations message should pass but it didn't. Could you please explain the reason?    
Reply all
Reply to author
Forward
0 new messages