【发布时间】:2013-03-16 08:51:24
【问题描述】:
对于更高级的 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
controllers/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
【问题讨论】:
-
Product模型是否有任何验证?可以同时发布该模型和您为其定义的 Factory_girl 吗? -
谢谢!我不会发布模型和验证,而是继续让您知道这是问题所在(factories.rb 文件中的错字触发了验证错误)。嘿,现在我知道将来要寻找什么了!
-
你应该要么使用
create!处理任何异常,要么使用create并通过@product.valid?或@product.persisted?之类的方式检查记录是否有效,并处理验证失败。跨度> -
谢谢吉姆,这是一个很好的提示。我对 RSpec 比较陌生,感觉有很多像你刚才提到的我目前不知道的好技巧,而且我不确定我会在哪里找到它们。再说一次,在 Stack Overflow 上乐于助人的人也是一个很好的来源!
标签: ruby-on-rails rspec controller