[rspec-users] Mock and Stub objects

David Chelimsky dchelimsky at gmail.com
Fri Jun 12 10:38:14 EDT 2009


On Fri, Jun 12, 2009 at 4:46 AM, Amit Kulkarni<lists at ruby-forum.com> wrote:
> Even if we are using mocks and if our models are changed then also we
> need to change our spec.
> Same for if we don't use mocks.

This is true in some cases, but not in many of the common cases.
Here's an example:

describe WidgetsController do
  describe "POST create" do
    context "with valid attributes" do
      WidgetsController.stub(create!).and_return(true)
      post :create
      response.should redirect_to(widgets_path)
    end

    context "with invalid attributes" do
      WidgetsController.stub(create!).and_raise(ActiveRecord::RecordInvalid(mock_model(Widget)))
      post :create
      response.should render_template('new')
    end
  end
end

These two examples will never have to change due to a change in model
validation rules. The only reason they'd ever have to change would be
if you wanted to make a change the controller itself and how it
handles the create() action.

In this case we're using stubs, not mocks, but they are serving the
purpose of isolating change.

> So same question i am asking Are mocks really useful?
> Also When to use if at all we want to use?
> I searched on net regarding the same but till now no success :-)

Amit - you don't have to search the net. Steve, Matt and I have all
taken valuable time to try to explain this to you, and Matt even
posted some very useful links for you. From this thread, the RSpec
book, and those links, you've got enough information in front of you
to start answering these questions for yourself. Please take some time
to read some of this stuff. If you have any specific questions about
any of that reading material, please feel free to ask them.

Cheers,
David

>
> Also i had started writing controller specs without using mocks just to
> see how it works?Will it be ok?

You'll be fine if you don't use mocks. I'd be fine if I didn't use
mocks. I happen to know how and when to use them so I like to use
them.

Cheers,
David

> --
> Posted via http://www.ruby-forum.com/.
> _______________________________________________
> rspec-users mailing list
> rspec-users at rubyforge.org
> http://rubyforge.org/mailman/listinfo/rspec-users
>


More information about the rspec-users mailing list