Home > OS >  Testing a chained set of commands with RSpec
Testing a chained set of commands with RSpec

Time:09-15

I have the following code:

Rails.cache.redis.ping == "PONG"

and I'm trying to write a spec to stub this response so that I can control what it returns in tests. However, usual simple expectations don't seem to work here as it's a method chain.

How would I test this code in RSpec?

CodePudding user response:

Rails.cache.redis returns an object of Redis class and the ping method is basically being called on an instance of the class. Here is how you can stub the ping method.

allow_any_instance_of(Redis).to receive(:ping).and_return(DESIRED_MOCK_VALUE)

CodePudding user response:

You can use before block and stub the chain of messages

before do
  allow(Rails).to receive_message_chain(:cache, :redis, :ping).and_return("PONG")
end
  • Related