在Rails控制器规范中模拟外部类

时间:2012-01-07 03:04:06

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

我有一个Rails 3应用程序,我正在使用RSpec进行测试。我有一个使用外部类MustMock作为

的控制器
class FooController < ApplicationController
  def myaction
    mockme = MustMock.new
    @foobar = mockme.do_something
  end
end

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

2 个答案:

答案 0 :(得分:5)

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