【问题标题】:RSpec - Controller Specs with no corresponding viewsRSpec - 没有对应视图的控制器规范
【发布时间】: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


【解决方案1】:

如果您真的不想呈现响应,请使用此而不是重定向。

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

您当前的代码无法创建产品,并且创建调用返回 false,但您没有检查它。使用创建!如果创建失败会为你抛出错误,否则你需要检查 create 的返回值并处理返回值是 true 还是 false 的逻辑。如果你不这样做,你会得到无声的失败,这是最糟糕的失败。

【讨论】:

  • 感谢您的建议!我已切换到 head :ok 并添加了错误渲染,但我的代码仍然允许我通过 RailsAdmin 以及 Rails 控制台创建产品。
  • 我认为这是预期的行为。问题是您的测试没有创建模型。您想在测试代码中查看模型上的错误。它可能会显示您需要在 FactoryGirl 工厂中进行更改的明显内容。
【解决方案2】:

对于第一种情况response.should be_success 只通过 如果返回状态码 200。在您的情况下,您将重定向到 home 所以 状态码将在300 - 399 之间。将第一个测试更改为:

 response.should be_redirect

目前还不确定第二个。

【讨论】:

  • 谢谢!一个下来,一个去。我并不真的“需要”重定向,但是如果没有重定向行,我会收到一条错误消息,指出没有相应的视图。如果您对此事有任何想法,请随时告诉我。
猜你喜欢
  • 1970-01-01
  • 2013-01-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多