对于更高级的Rails开发人员来说,这是一个简单的问题,但我无法确定答案。我有两个非常基本的控制器规格没有通过。我没有关联的视图(我正在通过RailsAdmin
添加/删除产品)但这应该不是问题,因为在控制器中我正在重定向每个操作。
下面附有相关代码。非常感谢帮助。谢谢!
products_controller_spec.rb 需要'spec_helper'
describe ProductsController do
describe 'GET #new' do
it "creates a new product" do
get :new
response.should be_success
end
end
describe 'POST #create' do
it "creates a new product and saves it" do
expect{
post :create, product: FactoryGirl.attributes_for(:product)
}.to change(Product, :count).by(1)
end
end
end
控制器/ products.rb
class ProductsController < ApplicationController
def new
@product = Product.new
redirect_to 'home'
end
def create
@product = Product.create(params[:product])
redirect_to 'home'
end
end
错误讯息:
Failures:
1) ProductsController GET #new creates a new product
Failure/Error: response.should be_success
expected success? to return true, got false
# ./spec/controllers/products_controller_spec.rb:7:in `block (3 levels) in <top (required)>'
2) ProductsController POST #create creates a new product and saves it
Failure/Error: expect{
count should have been changed by 1, but was changed by 0
# ./spec/controllers/products_controller_spec.rb:13:in `block (3 levels) in <top (required)>'
Finished in 0.07747 seconds
2 examples, 2 failures
答案 0 :(得分:4)
如果您不想呈现响应,请将其替换为重定向。
head :ok
您应该使用Product.create!
def create
Product.create!(params[:product])
head :ok
end
或检查Product.create的返回结果
def create
if Product.create(params[:product])
head :ok
else
head :unprocessable_entity
end
end
甚至更好,在回复中返回错误
def create
product = Product.new(params[:product])
if product.save
head :ok
else
render json: product.errors
end
end
您当前的代码无法创建产品,并且对create的调用返回false,但您没有检查它。使用创建!如果创建失败,将为您抛出一个错误,否则您需要检查create的返回值并处理返回值为true或false的逻辑。如果你不这样做,你会得到无声的失败,这是最糟糕的失败。
答案 1 :(得分:2)
对于第一种情况,response.should be_success
仅通过
如果返回了200
的状态代码。在您的情况下,您将重定向到home
状态代码将介于300 - 399
之间。将第一个测试更改为:
response.should be_redirect
还不确定第二个。