mardi 29 septembre 2015

How to mock model attributes with Rspec?

I have a controller action with something like:

    @widget = Widget.new(permitted_params)
    @widget.user_id = current_user.id

    if @widget.save
      @widget
    else
      { errors: @widget.errors.full_messages }
    end

And I'm trying to create a spec for that controller.

widget = mock_model(Widget)

allow(Widget).to receive(:new).and_return(widget)
allow(widget).to receive(:user_id).and_return(widget)
allow(widget).to receive(:save).and_return(true)

expect(widgets).to receive(:build)
expect(widget).to receive(:save)
post '/v2/widgets', name: 'foo'
expect(json_response).to eq widget.as_json

Now the weird thing that I'm getting :

 Failure/Error: post '/v2/widgets', name: 'foo'
   #<Double "Widget_1133"> received unexpected message :user_id= with (1129)

Even when I have

allow(widget).to receive(:user_id).and_return(widget)

Any help what is the mistake i'm doing?

Thanks

Aucun commentaire:

Enregistrer un commentaire