我的研讨会应用程序存在问题,我现在正在做。我无法修复测试中的两个最后错误。在我看来,应用程序在浏览器中运行良好。也许测试有问题?任何帮助将不胜感激。
两个错误:
1) ProductsController PUT update with valid params updates the requested product
Failure/Error: Unable to find matching line from backtrace
Exactly one instance should have received the following message(s) but didn't: update
2) ProductsController PUT update with invalid params re-renders the 'edit' template
Failure/Error: response.should render_template("edit")
expecting <"edit"> but rendering with <[]>
测试代码:
require 'spec_helper'
describe ProductsController do
let(:category) { create(:category) }
let(:valid_attributes) { { "title" => "MyString", "category_id" => category.id, "price" => 5.59,
"description" => "Lorem ipsum dolor sit amet"} }
let(:valid_session) { {} }
describe "PUT update" do
let(:user) { build(:user) }
before do
sign_in user
controller.stub(:user_signed_in?).and_return(true)
controller.stub(:current_user).and_return(user)
controller.stub(:authenticate_user!).and_return(user)
end
describe "with valid params" do
it "updates the requested product" do
product = Product.create! valid_attributes
Product.any_instance.should_receive(:update).with({ "title" => "MyString" })
put :update, { id: product.to_param, product: { "title" => "MyString" }, category_id:
category.to_param }, valid_session
end
describe "with invalid params" do
it "re-renders the 'edit' template" do
product = Product.create! valid_attributes
Product.any_instance.stub(:save).and_return(false)
put :update, { id: product.to_param, product: { "title" => "invalid value" }, category_id:
category.to_param }, valid_session
response.should render_template("edit")
end
end
end
end
ProductsController#update code:
def update
if self.product.update(product_params)
redirect_to category_product_url(category, product), notice: 'Product was successfully
updated.'
else
render action: 'edit'
end
end
答案 0 :(得分:0)
一般
expecting <"edit"> but rendering with <[]>
通常这意味着您需要渲染(例如,在验证失败后)并且您的控制器执行重定向(在成功保存模型之后)
代码
你在这里存根save
方法:
Product.any_instance.stub(:save).and_return(false)
但请调用使用update
方法的操作
if self.product.update(product_params)
所以行动成功 - &gt;你的控制器重定向 - &gt;您的“修改”模板未呈现 - &gt;你的规格失败
您的解决方案
而不是存根save
,你应该存根valid?
,这是一种很好的做法
Product.any_instance.stub(:valid?).and_return(false)