入门

安装 Rails

$ gem install rails -v "~> 7.2.0"

生成应用程序

$ rails new example_app
$ cd example_app

将 `rspec-rails` 添加到 Gemfile

$ echo 'gem "rspec-rails", group: [:development, :test]' >> Gemfile

安装捆绑包

$ bundle install

引导 RSpec

$ rails generate rspec:install

生成脚手架

$ rails generate scaffold Widget name:string

这将在 `app` 和 `spec` 目录中生成文件。 `app` 目录中的文件由 Rails 生成,Rails 将 `spec` 目录中文件的生成委托给 RSpec。

运行迁移

$ rails db:migrate && rails db:test:prepare

运行 RSpec

$ rake spec

或者

$ rspec spec --format documentation

如果一切顺利,您应该看到以以下内容结尾的输出

29 examples, 0 failures, 2 pending

此输出还包含以下控制器规范

WidgetsController
  GET index
    assigns all widgets as @widgets
  GET show
    assigns the requested widget as @widget
  GET new
    assigns a new widget as @widget
  GET edit
    assigns the requested widget as @widget
  POST create
    with valid params
      creates a new Widget
      assigns a newly created widget as @widget
      redirects to the created widget
    with invalid params
      assigns a newly created but unsaved widget as @widget
      re-renders the 'new' template
  PUT update
    with valid params
      updates the requested widget
      assigns the requested widget as @widget
      redirects to the widget
    with invalid params
      assigns the widget as @widget
      re-renders the 'edit' template
  DELETE destroy
    destroys the requested widget
    redirects to the widgets list

像这样的输出可以帮助快速了解对象的行为。 它还显示了哪些情况已经指定,哪些情况尚未指定。 注意 `create` 和 `update` 操作示例之间的平衡。 如果 `redirects to the widget` 示例在其中一个或另一个中缺失,则很容易发现。

查看生成的 `spec/controllers/widgets_controller_spec.rb`,了解如何组织规范以生成类似的输出。