【问题标题】:rails rspec stub and raise a respond code 404 respondrails rspec 存根并引发响应代码 404 响应
【发布时间】:2014-01-09 19:04:57
【问题描述】:

我正在尝试为我的一个控制器编写一些 rspec 联合测试,但我对存根 REST api 调用有点困惑。

所以我有这个 REST 调用,它获取水果 id 并返回特定的水果信息,我想测试 REST 何时给我响应代码 404(未找到)。理想情况下,我会将方法调用存根并返回错误代码

在控制器中

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                    <----------- I think this is my problem

    get :show, {id: 'wrong_id'}
  end

  it 'receives 404 error code' do 
    expect(response.code).to eq('404')
  end

end 

这个给这个

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

【问题讨论】:

  • 您的测试超出了您正在存根的上下文

标签: ruby-on-rails ruby unit-testing rspec


【解决方案1】:

您没有在控制器中处理响应。我不确定您的 API 在 404 的情况下返回什么。如果它只是引发异常,那么您将不得不修改您的代码并进行一些测试。假设你有一个索引操作

def show 
  @fruit = FruitsService::Client.get_fruit(params[:id])
rescue Exception => e
  flash[:error] = "Fruit not found"
  render :template => "index"
end 

describe '#show' do  
  it 'receives 404 error code' do 
    FruitsService::Client.stub(:get_fruit).with('wrong_id').and_raise(JSON::ParserError)

    get :show, {id: 'wrong_id'}

    flash[:error].should == "Fruit not found"
    response.should render_template("index")
  end

end 

【讨论】:

  • 我刚刚发现 REST API 调用实际上会抛出一个 WebapplicationException 并且当 id 不存在时它会返回一个 JSON 字符串“提供的水果 id 为 null”。我在想是否有办法存根并引发该异常
  • Rails 会通过不同类型的异常处理 WebapplicationException。在救援块内打印e.class 以找出异常类型并在测试中引发相同的异常
  • 刚刚发现它原来是 JSON::ParserError 所以我猜我的起源想法是 FruitsService::Client.any_instance.stub(:get_fruit).with('wrong_id').and_raise( JSON::ParserError)
  • 或者无论如何我可以期待这个例外??
  • 是的,修改了我的答案。不要使用FruitsService::Client.any_instanceany_instance 用于在 FruitsService::Client 的对象上调用方法时使用。在您的情况下,您正在调用类方法
猜你喜欢
  • 2012-12-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-12
  • 1970-01-01
相关资源
最近更新 更多