A
A
Anton Ivanov2019-05-11 15:10:11
Ruby on Rails
Anton Ivanov, 2019-05-11 15:10:11

How can I force a module method to return what it needs in rspec using the new syntax?

Hello.
RSpec 3.8
Rails 5.2.1
There is a module:

module X
  included do
    after_create :test_method
  end

  def test_method
    ...
  end
end

and there is a model that uses this method:
class ParentModel < ApplicationRecord
  include X
end

there is also a model that is a child of ParentModel
class ChildModel < ApplicationRecord
  belongs_to :parent_model
end

In tests, the ChildModel is created by the FactoryBot, which automatically causes the parent model to be instantiated and the method from module X to be called.
The goal is to get the test_method method to return what we want.
How it's done now:
parent_model = ParentModel.new
  allow(ParentModel).to receive(:new).and_return(parent_model)
  allow(parent_model).to receive(:test_method).and_return(true)

  child_model = FactoryBot.create(:child_model)

everything works, but, for some reason, I don't like it :) the
old RSpec syntax allows you to use allow_any_instance_of, but they themselves write that this is a code smell.
How to do it right? Or is everything done right now?
Thank you.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
oh_shi, 2019-05-11
@Fly3110

Everything is fine, now this is the syntax. allow_any_instance_offor some time it will display messages that it is "deprecated". And after a few versions it will be completely removed.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question