【问题标题】:rails rspec matcher for exception with a stub method带有存根方法的异常的rails rspec匹配器
【发布时间】:2014-01-12 02:06:42
【问题描述】:

我无法让匹配器捕获异常。控制器方法只需执行 REST 调用并获取带有 id 的水果,我想测试 REST 何时给我一个错误响应,在 rails 中是 JSON::ParserError。我想测试这个案例,所以我将 REST 调用存根并引发异常。

我知道存根工作的事实,因为我得到了那个确切的错误。我相信我只需要一个匹配器来在调用 get 时捕获错误

In Controller  

def show 
  @fruit = FruitsService::Client.get_fruit(params[:id])
end 

spec/controller/fruits_controller_spec.rb

describe '#show' do
  before do    
    context 'when a wrong id is given' do 
        FruitsService::Client.any_instance
          .stub(:get_fruit).with('wrong_id')
          .and_raise(JSON::ParserError)
  end

  it 'receives 404 error code' do 
    get :show, {id: 'wrong_id'}   <------ I think I might need a matcher for this ? 
    expect(FruitsService::Client.get_fruit('wrong_id')).to raise_error(JSON::ParserError)
  end

end 

这个给这个

 Failure/Error: get :show, {id: 'wrong_id'}
 JSON::ParserError:
   JSON::ParserError

【问题讨论】:

    标签: ruby-on-rails rest rspec rspec-rails


    【解决方案1】:

    当你想测试行为时,比如引发错误,你需要传递一个块给expect而不是一个参数,如:

    it 'receives 404 error code' do 
      expect { get :show, {id: 'wrong_id'} }.to raise_error(JSON::ParserError)
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-26
      • 1970-01-01
      • 2013-07-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多