在Rspec中为Update方法编写测试用例

时间:2013-08-20 05:26:22

标签: ruby-on-rails ruby rspec

我正在为控制器的更新方法编写Rspec,该控制器使用给定的标识T更新表ID中的记录。在规范中我想添加一个案例,检查表ID中是否存在T的任何记录,如果它不存在,它应该给出如下的错误但是我是RSpec的新手我可以没完成它。

  it "should give error when record with the given id does not exist" do
    pending "case yet to be handled"
  end

所以如果有人帮我写这个规范。

2 个答案:

答案 0 :(得分:0)

您可以执行Model.find并检查此记录是否不存在。

it "should give error when record with the given id does not exist" do
    expect { Model.find(<your ID>) }.should raise_error(ActiveRecord::RecordNotFound::Error)
end

答案 1 :(得分:0)

您应该传递参数id并使用正确的HTTP谓词来发送更新操作请求。即

it "should give error when record with the given id does not exist" do
    put :update, id: <invalid_id>
    # you expectations here    
end

How I learned to test my Rails applications, Part 4: Controller spe对控制器测试有一些示例和更多解释。

相关问题