Pergunta

Here the docu: https://relishapp.com/rspec/rspec-mocks/v/3-0/docs/message-expectations/expect-a-message-on-any-instance-of-a-class

Im wondering what is the right use of it.

I have a controller

class UserController < ApplicationController
  def edit
    generate_token!
  end
end

And the method generate_token! is defined in the model.

class User < ActiveRecord::Base
  def generate_token!
    self.update!(token: 'something')
  end
end

I just want to check if the method receives something. The spec would be something like.

describe 'edit'
  it 'receives something' do
    expect_any_instance_of(Object).to receive(:generate_token!)
  end
end

But what do I have to use for the Object? I tried the class and some other random stuff, but nothing worked yet. It seems I dont get the Mock at all. Any suggestions?

best regards denym_

Foi útil?

Solução

You need to replace Object with Client in your spec. Also the method's name is only "generate_token" not "generate_token!" as you have in your spec currently.

It seems you are mixing the generate_token! in your controller and the generate_token method in your Client model.

In the edit action you are calling the generate_token! defined in the same class (controller) (I would assume you only pasted the edit action here, so you might really have this method in your controller). Anyway, if you do not have a generate_token! method in your controller which has a line like that:

@client.generate_token

the generate_token inside your Client model will never get called from your controller.

One more thing: the name of the controller that handles your client records really called users_controller?

That could also cause problem, if you really have a separate User and Client model.

I think now I know what could be your main confusion.

Expect only set your expectation. You still need to create the instance of the class and trigger the action where you are expecting something that you want to see to happen.

Eg. if you are testing a controller action you need to call the edit action after you set your expectation.

client = create(:client)
get :edit, id: client
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top