Mocking a non database backed model in Rails with Rspec
I am trying to create a non ActiveRecord model in my Ruby on Rails application according to http://railscasts.com/episodes/121-non-active-record-model. I am facing hard time testing it though.
I have following class in my app/models/sms.rb
file.
class Sms
def initialize
# Do stuff here
end
def deliver
# Do some stuff here
end
end
I am unable to mock deliver method on my Sms class.
it 'should do someting' do
@sms = mock(Sms)
@sms.should_receive(:deliver).and_return(true)
post :create, :user_id => @user.id
flash[:notice].should == "SMS sent successfully."
response.should redirect_to(some_url)
end
In my controller code I do have a line that says @sms.deliver
. Yet above gives following error:
Failure/Error: @sms.should_receive(:deliver).and_r开发者_StackOverflow中文版eturn(true)
(Mock Sms).deliver(any args)
expected: 1 time
received: 0 times
Any pointers?
Variables beginning with @ are instance variables. The @sms your controller refers to is not the same @sms as your spec has defined.
Try changing
@sms = mock(Sms)
@sms.should_receive(:deliver).and_return(true)
to
Sms.any_instance.should_receive(:deliver).and_return(true)
If your version of RSpec doesn't have the any_instance
method, you'll need to stub :new
on the class:
@sms = mock(Sms)
Sms.stub(:new).and_return(@sms)
@sms.should_receive(:deliver).and_return(true)
精彩评论