使用Railscast#53的自定义异常处理时,RSpec控制器规格错误地失败 [英] RSpec controller spec incorrectly failing when using custom exception handling from Railscast #53

查看:235
本文介绍了使用Railscast#53的自定义异常处理时,RSpec控制器规格错误地失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有之前提到这个问题,并被指示到这个问题的答案适用于功能规格。

I had asked this question before and was directed to this question for an answer that worked with feature specs.

但是,我仍然遇到规范失败与ActiveRecord :: RecordNotFound错误时包括在控制器规格。例如,项目#新建和项目#创建操作应该需要一个:list_id param。 (我将使用一个嵌套的路由: lists /:list_id / items / new 。)如果没有:list_id 由于无法加载@list,因此引发了ActiveRecord :: RecordNotFound。 自定义异常处理会导致重定向到自定义错误#404。但是,我有一个控制器规范:

However, I'm still running into the spec failing with an ActiveRecord::RecordNotFound error when including this in a controller spec. For example, the items#new and items#create actions should require a :list_id param. (I'd be using a nested route: lists/:list_id/items/new.) If no :list_id, an ActiveRecord::RecordNotFound is raised because it can't load @list. The custom exception handling causes a redirect to the custom errors#404. However, I have this in a controller spec:

# /spec/controllers/items_controller_spec.rb
describe "list_id param is missing" do
  { new: :get, create: :post }.each do |action, method|
    it "Redirects to the custom 404" do
      send(method, action)
      # need something here to test that it ultimately ends up at the custom 404 page.
    end
  end
end

# /config/environments/test.rb
config.consider_all_requests_local       = false
config.action_controller.perform_caching = false

在浏览器中,这正确地重定向到了404.但测试错误地失败:

In the browser this correctly redirects to a 404. However the test incorrectly fails:

 Failure/Error: send(method, action)
 ActiveRecord::RecordNotFound:
   Couldn't find List without an ID

正如我在上面链接的其他问题中提到的,功能规格工作正常,但是如何我得到这个工作与控制器规格? (Rails 4 app)

As mentioned in the other questions I linked to above, feature specs work fine, but how can I get this work with controller specs? (Rails 4 app)

更新:某些控制器代码:

# /app/controllers/items_controller.rb
before_action :set_list, only: [:new, :create]

def new
  @item = @list.items.build
end

private

def set_list
  @list = current_user.lists.find(params[:list_id])
end


推荐答案

我没有实现你的做法(我不能确定它是否正确)。通常,您可以隔离每个案例的测试,即GET,POST请求。尝试一下,看看问题是否仍然存在?

controller spec is different though. I haven't implemented the way you are doing(which I can't tell whether it's correct or not). Normally you isolate the test for every single cases ie GET, POST requests. Try that and see if the problem still persist?

这篇关于使用Railscast#53的自定义异常处理时,RSpec控制器规格错误地失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆