这是rspec中的错误:
CategoriesController GET 'update' should be successful
Failure/Error: get 'update'
ActiveRecord::RecordNotFound:
Couldn't find Category without an ID
# c:in `find'
# ./app/controllers/categories_controller.rb:45:in `update'
# ./spec/controllers/categories_controller_spec.rb:35:in `block (3 levels) in <top (required)>'
以下是控制器中的代码:
def edit
@category = Category.find(params[:id])
end
def update
@category = Category.find(params[:id])
#@category.reload. caused nil.reload error
if @category.update_attributes(params[:category], :as => :roles_update)
@category = Category.find(params[:id])
redirect_to @category, :notice => 'Category was successfully updated'
else
@categories = Category.all
render 'index'
end
end
这是rspec代码:
describe "GET 'update'" do
it "should be successful" do
get 'update'
response.should be_success
end
end
有什么想法?感谢。
答案 0 :(得分:1)
您粘贴了创建操作而不是更新操作。此外,您正尝试使用get请求测试更新操作..如果您遵循约定,则应该使用put请求。
如果您已经实施了更新操作......您可能会或多或少地测试:
describe CategoriesController do
let(:category) { mock_model(Category).as_null_object }
describe "PUT update" do
before do
Category.should_receive(:find).with(5).and_return(category)
end
context "when a category updates succesfully" do
before do
category.stub(:update_attributes).and_return(true)
end
it "redirects to the categories page" do
put :update, :id => 5, :category => { :some_val => 4 }
response.should redirect_to(categories_path)
end
it "sets the flash message" do
put :update, :id => 5, :category => { :some_val => 4 }
flash[:notice].should eq("Category was succesfully updated")
end
end
context "when a category does not update successfully" do
before do
category.stub(:update_attributes).and_return(false)
end
it "sets the flash message"
it "redirects to the categories page"
# etc etc
end
end
end
为了达到这一点(意味着添加了模拟模型,存根,你有什么),你通常会开始“新鲜”,所以说起来并以TDD风格的方式工作。希望它有所帮助