我正在尝试为我的一个控制器编写一些 rspec unite 测试,并且我对存根 REST api 调用运行了一点困惑。
所以我有这个 REST 调用,它获取水果 id 并返回特定的水果信息,我想测试 REST 何时给我响应代码 404(未找到)。理想情况下,我会存根方法调用并返回错误代码
在控制器中
def show
@fruit = FruitsService::Client.get_fruit(params[:id])
end
规格/控制器/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
您没有在控制器中处理响应。我不确定您的 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