我正在为以下一种控制器方法编写单元测试:
try (final ByteArrayInputStream bais = new ByteArrayInputStream(csrAsString.getBytes());
final InputStreamReader isr = new InputStreamReader(bais, StandardCharsets.UTF_8);
final PEMParser pem = new PEMParser(isr))
{
PKCS10CertificationRequest csr = (PKCS10CertificationRequest) pem.readObject();
// Do your verification here
}
此路线为:
def update
@key = current_user.keys.find_by_key(params[:id])
@key.update_attributes(key_params)
redirect_to :back
end
private
def key_params
params.require(:key).permit(:note)
end
到目前为止,我有以下内容:
PUT /projects/:project_id/keys/:id keys#update
但这会产生如下错误:
describe '#update' do
before :each do
@user = FactoryGirl.create(:user)
@project= FactoryGirl.create(:project, user: @user)
@key = FactoryGirl.create(:key, id: 40, project: @project, user: @user)
controller.stub(:current_user).and_return(@user)
end
it 'update key' do
put :update, project_id:@project.id, id:@key.id
expect(response.code).to eq "302"
end
end
任何线索都将非常有帮助。 谢谢
答案 0 :(得分:1)
您需要将关键参数传递给操作。不仅要检查响应状态,还要检查操作结果,这是个好主意
it 'updates key' do
# supposing that "note" is a string column
expect do
put :update, project_id: @project.id, id: @key.id, key: { note: 'New note' }
end.to change { @key.note }.from('Old note').to('New note')
expect(response.code).to eq "302"
end
更新:
在控制器中,您尝试按键属性查找键实例
@key = current_user.keys.find_by_key(params[:id])
但是您要在规范中传递key.id。它如何在应用程序中工作?我想,您将密钥作为:id
参数传递了,所以应该是
put :update, project_id: @project.id, id: @key.key, key: { note: 'New note' }
根据您的规格。同样,find_by_key
如果找不到任何内容也不会引发错误,它只会返回nil。这意味着您不会得到RecordNotFound。此外,这是一个已弃用的方法,您应该使用find_by(key: params[:id])
要引发错误,请使用bang方法find_by!(key: params[:id])
如果您在应用中传递key.id
,则需要在控制器操作中进行更改
@key = current_user.keys.find(params[:id])