简体   繁体   English

Ruby,Rspec和要求测试的控制器

[英]Ruby, Rspec, and requiring test contoller

I'm new to Ruby (RoR) and rspec. 我是Ruby(RoR)和rspec的新手。

I have the basic project scaffold and a controller within project/app/controllers/books_controller.rb 我在project/app/controllers/books_controller.rb有基本的项目支架和控制器

Then I'm trying to setup rspec in project/spec/controllers/book_spec.rb 然后我试图在project/spec/controllers/book_spec.rb设置rspec

There also exists project/spec/spec_helper.rb that book_spec.rb requires. 还存在book_spec.rb所需的project/spec/spec_helper.rb This file is where I'm trying to include the books_controller.rb file. 该文件是我尝试包含books_controller.rb文件的位置。

How do I include the books_controller.rb file so book_spec.rb has the Book object so when I run rspec, it works? 如何包含books_controller.rb文件,使book_spec.rb具有Book对象,因此在我运行rspec时可以工作吗?

Currently I've tried things like require_relative "../app/controllers/books_controller" and it doesn't work. 目前,我已经尝试过诸如require_relative "../app/controllers/books_controller"类的东西,但是它不起作用。 It gives me an error like: 它给我一个错误,如:

uninitialized constant ApplicationController ... in 'require_relative'

Any help would be great. 任何帮助都会很棒。

You don't need to manually include your controllers, just follow the rspec naming conventions and describe the desired object and everything will work fine. 您无需手动包括控制器,只需遵循rspec命名约定并描述所需的对象,一切都会正常进行。

Your controller spec should be named books_controller_spec.rb . 您的控制器规格应命名为books_controller_spec.rb That is the exact same name as your controller with a _spec added at the end. 该名称与控制器的名称_spec并在末尾添加_spec This is not a hard requirement but a highly suggested convention as a book_spec.rb really implies a Book model spec rather than a controller. 这不是一个硬性要求,而是一个强烈建议的约定,因为book_spec.rb实际上暗示着Book模型规范而不是控制器。

The critical part is that in your spec you describe the desired object, eg 关键部分是在您的规范中描述了所需的对象,例如

describe BooksController do
  #...
end

You might also want to have a look at the rspec-rails gem which provides some useful generators for specs. 您可能还想看看rspec-rails gem,它为spec提供了一些有用的生成器 Ideally you integrate with Rails so whenever you generate a new model or controller a new spec is created for you as well. 理想情况下,您需要与Rails集成,因此,无论何时生成新模型或控制器,都会为您创建新规范。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM