Reputation: 129
I have an ActiveRecord object User. In the app I am making I am using a single sign on gem, but I need to save some of the user data in our databse. My ApplicationController has this code:
def create_user
User.create(name: current_user['name'], email: current_user['email'], company_id: current_user['id'])
end
I need an RSpec test that mocks out the actual create
call. I have tried
allow_any_instance_of(User).to receive(:create).with(any_args).and_return(user)
which returns an error saying "User does not implement create".
Upvotes: 4
Views: 4077
Reputation: 37617
jvillian is correct that the problem is that create
is implemented by User
, not by an instance of User
. The simple fix is just to stub the method directly on User
(i.e. use allow
instead of allow_any_instance_of
):
allow(User).to receive(:create).with(any_args).and_return(user)
Also, .with(any_args)
is a no-op, so this is equivalent:
allow(User).to receive(:create).and_return(user)
Upvotes: 6
Reputation: 20263
I'm thinking that allow_any_instance_of
is expecting an instance of User
to implement create
. create
, however, is a class method. So, I believe the error messages is saying that instances of User
don't implement create
.
I'd suggest seeing if class_double
works for your use case. Check out Rspec Mocks and this SO post from Myron Marston.
Upvotes: 2