Mr Robot Arms Mr Robot Arms - 1 year ago 83
Ruby Question

How to mock the create call for a new ActiveRecord object in RSpec?

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'])

I need an RSpec test that mocks out the actual
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".

Answer Source

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)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download