0

我想验证是否在我想使用 rspec 注入 Sinatra 应用程序的服务上调用了一个方法,但我找不到如何完成此操作的示例。这是我的规格...

RSpec.configure do |config|
  config.include Rack::Test::Methods
end

def app
  App
end

describe 'Login' do
  context 'when the user is logged out' do
    describe 'POST on /signup' do
      it 'invokes signup on the user service with the correct parameters' do
        service = double('user_service').as_null_object
        service.should_receive(:signup).with(:username => 'RobA2345')
        post '/signup'
      end
    end
  end
end

这里的应用程序是一个模块化的 Sinatra 应用程序。我来自 .NET 背景,我会在这里使用构造函数注入来解决这个问题,但我知道这不是 ruby​​ 方法。

一如既往,感谢您的帮助。

4

1 回答 1

1

假设您希望在 的新实例上接收消息 UserService,有几种方法可以做到这一点。如果您使用的是最新版本的 rspec,这应该可以:

it 'invokes signup on the user service with the correct parameters' do
  UserService.any_instance.should_receive(:signup).with(:username => 'RobA2345')
  post '/signup'
end

或者,这应该适用于几乎任何版本的 rspec:

it 'invokes signup on the user service with the correct parameters' do
  service = double('user_service').as_null_object
  UserService.stub(:new).and_return(service)
  service.should_receive(:signup).with(:username => 'RobA2345')
  post '/signup'
end
于 2013-04-23T13:24:54.410 回答