【问题标题】:stub an instance variable inside controller存根控制器内的实例变量
【发布时间】:2013-01-16 15:39:36
【问题描述】:

我正在使用 rspec 1.3.2 来测试一个看起来像这样的控制器操作:

def action_foo
  ...
  @bar.can_do_something?
  ...
end

我正在尝试存根 @bar(假设它是类 Bar 的一个实例)实例变量,但我无法做到。我想如果我可以访问any_instance,那么我可以使用Bar.any_instance.stub(:can_do_something?),但这在我正在使用的 rspec 版本中不可用。

还有其他方法可以访问和存根@bar吗?以下方法均无效:

@bar.stub(:can_do_something?)
controller.instance_variable_get("@bar").stub(:can_do_something?)
controller.stub_chain(:bar, :can_do_something?)
Bar.new.stub(:can_do_something?)

编辑:

@barbefore_filter 中分配。类似@bar = Bar.find(n)

【问题讨论】:

  • @bar 在哪里/如何实例化?
  • @barbefore_filter 中分配

标签: ruby-on-rails ruby rspec tdd


【解决方案1】:

为了记录,我认为这更清洁:

bar = Bar.new # or use FactoryGirl to create a Bar factory
bar.stub(:can_do_something?) { # return something }
controller.instance_variable_set(:@bar, bar)

【讨论】:

    【解决方案2】:
     Bar.any_instance.stub(:can_do_something?)
    

    【讨论】:

    • @barbefore_filter 中分配
    • 所以:Bar.should_receive(:find).and_return your_object_or_mock
    • 现在是allow_any_instance_of(Bar).to receive(:can_do_something?).and_return true
    【解决方案3】:

    如果所有其他方法都失败了,您可以执行类似于 any_instance.stub 的操作。郑重声明,这让我觉得很脏。

    Bar.class_eval do
      alias :original_can_do_something? :can_do_something?
    
      def can_do_something?  # "stub" method
        # Return whatever you need here
      end
    end
    
    # Run your test
    
    Bar.class_eval do
      alias :can_do_something? :original_can_do_something?  # "unstub" the method
    end
    

    【讨论】:

    • 我不会采用这个解决方案,而是接受您的回答,因为它是唯一回答我问题的解决方案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-24
    相关资源
    最近更新 更多