Home > Mobile >  Assert ActiveRecord method is called through class method with RSpec
Assert ActiveRecord method is called through class method with RSpec

Time:04-20

I'm stumped on what appears to be a fairly simple thing I'd like to do. I've got a pretty simple class:

class User
  def self.find_by_search(query)
    query = query.to_s.strip

    if query.upcase.start_with?("USER")
      find(query)
    else
      find_by(name: "*#{query}*")
    end
  end
end

I'd love to test that logic, so I simply need to assert that either find or find_by is called with the expected parameter. I've tried a couple of things:

User.find_by_search("USER0000")
expect(ActiveRecord::Base).to receive(:find)

and

User.find_by_search("USER0000")
expect(User).to receive(:find) # didn't really think this would work, but figured I'd try anyway

Both result in

expected: 1 time with any arguments
received: 0 times with any arguments

I must be doing something dumb here, but can't seem to figure it out.

CodePudding user response:

expect().to receive() should be define before we execute the operation.

expect(User).to receive(:find) 
User.find_by_search("USER0000")

Read more about expect(...).to receive(...)

  • Related