【问题标题】:Rails controller test with Rspec使用 Rspec 进行 Rails 控制器测试
【发布时间】:2020-02-11 00:00:17
【问题描述】:

我试图通过制作经常共享的部分html.erb 文件来组织代码(例如_form.html.erb

我想检查我的部分代码是否适用于不同的模型/控制器,所以我从视图中手动执行 CRUD。

使用Rspec 自动测试我的代码会更好,但我不知道。谁能给我一些指导如何使用Rspec 测试控制器代码?

【问题讨论】:

标签: ruby-on-rails ruby rspec


【解决方案1】:

要一起测试控制器和视图,您可以编写 feature specsrequest specs

请求规范是较低级别的规范,您可以在其中向应用程序发送 HTTP 请求并编写有关响应的期望(也称为 TDD 术语中的断言)。它们是ActionDispatch::IntegrationTest 的包装。请求规范应被视为控制器规范的替代品,RSpec 和 Rails 团队不鼓励使用控制器规范。

# spec/requests/products_spec.rb
require 'rails_helper'
RSpec.describe "Products", type: :request do
  describe "GET /products" do
     let!(:products) { FactoryBot.create_list(:product, 4) }
     it "contains the product names" do
        get "/products"
        expect(response).to include products.first.name
        expect(response).to include products.last.name
     end
  end
end

功能规范是侧重于用户故事的更高级别的规范。它们通常用作验收测试。他们使用名为 Capybara 的浏览器模拟器来模拟用户在应用程序中的点击方式。 Capybara 还可以通过 selenium 运行无头浏览器(无头 chrome、firefox、phantom js、webkit 等)和“真实”浏览器。 minitest 的等价物是 ActionDispatch::SystemTestCase,但 RSpec 功能并没有将其封装起来(minitest/testunit 花了几年的时间才赶上这里)。

# Gemfile
gem 'capybara'
# spec/features/products_spec.rb
require 'rails_helper'
RSpec.feature "Products" do
  let!(:products) { FactoryBot.create_list(:product, 4) }

  scenario "when a user views a product" do
    visit '/'
    click_link 'Products'
    click_link products.first.name
    expect(page).to have_content products.first.name
    expect(page).to have_content products.first.description
  end
end

此规范测试 products#index 和 products#show 操作以及根页面和相关视图。

这两种规格都有其优点和缺点。功能测试适用于测试大范围的应用程序,但很繁重。请求规范更快,更容易复制导致错误/问题的特定请求,但您基本上只是将 HTML 与高度受限的正则表达式匹配。

【讨论】:

    【解决方案2】:

    检查部分代码是否适用于不同的模型/控制器。您可以在控制器规格中添加render_views

    如何使用 Rspec 测试控制器代码? 阅读官方文档https://relishapp.com/rspec/rspec-rails/docs/controller-specs

    此页面可能会有所帮助:https://thoughtbot.com/blog/how-we-test-rails-applications

    【讨论】:

    • 不鼓励编写控制器规范。那篇文章已经有 6 年历史了,而且已经过时了。
    • 嗨@max,他要求进行控制器测试,然后我确实告诉了他想知道的内容。那篇文章于 2019 年更新。
    猜你喜欢
    • 1970-01-01
    • 2012-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多