1
class Foo
  def fizz(user)
    puts user
  end
end


let(:user){create(:user)} 

it do
    expect(Foo).to receive(:fizz).with(user)
end

I run this test in RSpec of Rails app. Test fails with below result

Foo received :fizz with unexpected arguments

-[#<User id: 1, .. ,  created_at: "2024-09-18 10:39:41.403908004 +0900", updated_at: "2024-09-18 10:39:41.579679422 +0900"]

+ [#<User id: 1, .. ,  created_at: "2024-09-18 10:39:41.403909000 +0900", updated_at: "2024-09-18 10:39:41.579679422 +0900"]

Reload Object

Considering the possibility that the error was caused by slight differences in the timing of when the data was saved in the database, such as created_at and updated_at, I used user.reload to synchronize the database values ​​with the values ​​in memory, but this is solve my problem.

let(:user){create(:user)} 

it do
    user.reload
    expect(Foo).to receive(:fizz).with(user)
end
Foo received :fizz with unexpected arguments

expected: (#<User id:1, .., created_at: "2024-09-18 10:39:41.403909000 +0900", updated_at: "2024-09-18 10:39:41.579679000 +0900")

got: (#<User id:1, .., created_at: "2024-09-18 10:39:41.403909000 +0900", updated_at: "2024-09-18 10:39:41.579679999 +0900")
6
  • 2
    Your test never executes #fizz. It cannot be the full test. Commented Sep 18, 2024 at 4:08
  • create(:user) also seems incorrect, should it be User.create? Please be sure you're posting the correct code which will reproduce your error. In both cases the created_at or updated_at is different. We need to see how user is used during the example. Commented Sep 18, 2024 at 4:13
  • 2
    1) Foo can't receive class method fizz, because you specify only instance method fizz, 2) it's better to use expect(...).to have_received(...).with(...), 3) if you expect something - you need to call code that will call this something Commented Sep 18, 2024 at 5:35
  • 2
    @Schwern create(:user) is most likely FactoryBot::Syntax::Methods#create. Commented Sep 18, 2024 at 12:27
  • This question is most likely a XY Problem. You're providing a spec that tells us nothing about the actual behavior your trying to test and the code doesn't even work to reproduce the problem. If I had to speculate what you actually need / want to is to test that the method is called with an instance of User and not that specific user or a completely different approach where you test the side effects of the method instead of poking inside. Spies are not always the best option. Commented Sep 18, 2024 at 12:35

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.