我正在尝试为我的一个控制器编写一些rspec unite测试,并且我正在运行int有点混淆关于存根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
答案 0 :(得分:0)
您没有在控制器中处理响应。我不确定在404的情况下你的API会返回什么。如果它只是引发异常,那么你将不得不修改你的代码并测试一下。假设你有一个索引动作
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