Rspec 如何存根在方法中创建的对象

Rspec how to stub an object created within a method

我正在重构一个臃肿的控制器,该控制器为旋转木马提供多态模型。我正在尝试构建一个 class 方法来处理查找和返回可轮播的项目。

在我的 RSPEC 测试中,我想将方法​​ 'is_something?' 存根在作为参数结果找到的场地上。

  def self.find_carouselable(params)
    .......
    elsif params[:venue_id].present?
      venue=Venue.friendly.find(params[:venue_id])
      if venue.is_something? 
        do this 
      else
        do that
      end
    end
  end

我无法弄清楚如何存根作为输入数据的结果创建的对象 - 我不确定这是否称为存根或模拟?

  context "carouselable is a venue" do 
    before do 
      allow(the_venue).to receive(:is_something?).and_return(true)
    end

    it "returns the instance of the carouselable object" do 
      expect(CopperBoxCarouselItem.find_carouselable(venue_params)).to eq the_venue
    end
   end

非常感谢

你只需要存根 Venue 位,像这样

      before do 
        allow(Venue).to receive(:friendly).and_return(some_venues)
        allow(some_venues).to receive(:find).and_return(venue)
        allow(venue).to receive(:is_something?).and_return(true)
      end

你应该可以做到:

allow_any_instance_of(Venue).to receive(:is_something?).and_return(true)

https://www.relishapp.com/rspec/rspec-mocks/v/2-14/docs/message-expectations/allow-a-message-on-any-instance-of-a-class