4

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".

Dave Schweisguth
  • 36,475
  • 10
  • 98
  • 121
Mr Robot Arms
  • 130
  • 2
  • 11

2 Answers2

6

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)
Dave Schweisguth
  • 36,475
  • 10
  • 98
  • 121
2

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.

Community
  • 1
  • 1
jvillian
  • 19,953
  • 5
  • 31
  • 44