【问题标题】:Mock external class in Rails controller spec在 Rails 控制器规范中模拟外部类
【发布时间】:2012-01-07 03:04:05
【问题描述】:

我有一个使用 RSpec 测试的 Rails 3 应用程序。我有一个控制器使用外部类MustMock as

class FooController < ApplicationController
  def myaction
    mockme = MustMock.new
    @foobar = mockme.do_something
  end
end

如何在我的控制器规范中最好地模拟 MustMock 的实例?

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-3 rspec rspec2


    【解决方案1】:
    describe FooController do
      specify :myaction do
        MustMock.should_receive(:new)
                .and_return(stub :do_something => :something)
        get :myaction
        assigns[:foobar].should == :something
      end
    end
    

    【讨论】:

    • +1,我非常喜欢这个块的形式。我要复制你的风格! :)
    【解决方案2】:

    你可以试试这个:

    it "does something in myaction" do
        my_stub = stub()
        my_stub.should_receive(:do_something).once.and_return(:foobar)
        MustMock.stub(:new => my_stub)
        get :myaction
        response.should be_success
    end
    

    【讨论】:

    • 一个小问题——我倾向于将response.should be_success 放在一个shared_example 中,因为在页面中需要它是很常见的。 YMMV
    • 是的,有几种方法可以改进测试。我怀疑 OP 的控制器动作更复杂,她/他将问题提炼成最小的可演示动作。
    • 完全同意,我确实是小意思:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多