如何使用 Capybara 在 Rails 中进行功能测试以及如何知道 500 错误?
How to do a feature test in Rails with Capybara and how to know 500 error?
我在 Rails 应用程序中创建了一条路线:
scope 'product' do
get '/', to: 'product#sort', as: 'product'
end
然后我想用 Capybara 测试我的功能:
# spec/features/product_spec.rb
require 'spec_helper'
feature 'Product', type: :feature do
describe 'Main page' do
context 'Before login' do
it 'Show product list' do
visit product_path
expect(page).to have_content('Product List')
end
end
end
end
但是我在终端里 运行 rspec 之后,它显示给我:
Failure/Error: expect(page).to have_content('Product List')
expected to find text "Product List" in "500 Internal Server Error"
为什么它给我一个 500 错误?发生了什么?如何查看错误详情?
在我的控制器和视图中,我设置了 @product_categories
:
在控制器中:
# app/controllers/product_controller.rb
class ProductController < ApplicationController
def sort
@product_categories = ProductCategory.all
@products = Product.all
end
end
在视图中:
# app/views/product/sort.html.erb
<h1>Product List</h1>
<% @product_categories.each do |category| %>
<%= category.name %>
<% end %>
<% @products.each do |product| %>
<%= product.name %>
<% end %>
是否有必要在规范测试源中定义该值?
您正在 class 上呼叫 .each
。我想你的意思是
@product_categories = ProductCategories.all
在你的控制器中。此外,按照惯例,您的控制器和视图文件夹名称应该是复数形式,因此 products_controller.rb
和 class 名称 ProductsController
和视图文件夹看起来像 app/views/products/sort.html.erb
。在你的路线中,也像这样 'products#sort'
.
复数控制器
至于您的测试,您似乎混合使用了 rspec 和水豚 DSL。如果使用功能,则不需要 :type => :feature
。您需要将 description
、context
和 it
合并为 scenario
。请参阅此处的使用带有 Rspec 内置 DSL 部分的水豚的示例:https://github.com/jnicklas/capybara
我在 Rails 应用程序中创建了一条路线:
scope 'product' do
get '/', to: 'product#sort', as: 'product'
end
然后我想用 Capybara 测试我的功能:
# spec/features/product_spec.rb
require 'spec_helper'
feature 'Product', type: :feature do
describe 'Main page' do
context 'Before login' do
it 'Show product list' do
visit product_path
expect(page).to have_content('Product List')
end
end
end
end
但是我在终端里 运行 rspec 之后,它显示给我:
Failure/Error: expect(page).to have_content('Product List')
expected to find text "Product List" in "500 Internal Server Error"
为什么它给我一个 500 错误?发生了什么?如何查看错误详情?
在我的控制器和视图中,我设置了 @product_categories
:
在控制器中:
# app/controllers/product_controller.rb
class ProductController < ApplicationController
def sort
@product_categories = ProductCategory.all
@products = Product.all
end
end
在视图中:
# app/views/product/sort.html.erb
<h1>Product List</h1>
<% @product_categories.each do |category| %>
<%= category.name %>
<% end %>
<% @products.each do |product| %>
<%= product.name %>
<% end %>
是否有必要在规范测试源中定义该值?
您正在 class 上呼叫 .each
。我想你的意思是
@product_categories = ProductCategories.all
在你的控制器中。此外,按照惯例,您的控制器和视图文件夹名称应该是复数形式,因此 products_controller.rb
和 class 名称 ProductsController
和视图文件夹看起来像 app/views/products/sort.html.erb
。在你的路线中,也像这样 'products#sort'
.
至于您的测试,您似乎混合使用了 rspec 和水豚 DSL。如果使用功能,则不需要 :type => :feature
。您需要将 description
、context
和 it
合并为 scenario
。请参阅此处的使用带有 Rspec 内置 DSL 部分的水豚的示例:https://github.com/jnicklas/capybara