【问题标题】:Rspec how to stub an object created within a methodRspec如何存根在方法中创建的对象
【发布时间】:2015-01-15 20:43:07
【问题描述】:

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

在我的 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

非常感谢

【问题讨论】:

    标签: ruby-on-rails ruby rspec


    【解决方案1】:

    你应该可以做到:

    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

    【讨论】:

      【解决方案2】:

      你只需要存根 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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-04-16
        • 1970-01-01
        • 2016-11-11
        • 2013-03-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多