[英]Rails RSPEC controller testing to count # of users on INDEX page
Working on controller testing and wanted to test that when I go to the index page, I should see the total number of users created and that should equal all the users that were in fact created. 进行控制器测试并想测试一下,当我进入索引页面时,我应该看到创建的用户总数,并且应该等于实际上创建的所有用户。 Can't get it to work and no errors are coming up, it just freezes and I have to press control c to exit.
无法正常工作,没有错误出现,只是死机,我必须按Control键退出。
describe "GET #index" do
it "show a list of all users" do
total = User.all.count
get :index
expect(response).to eq total
end
rspec controller tests don't render views by default, testing success might be better start rspec控制器测试默认情况下不渲染视图,测试成功可能是更好的开始
describe "GET #index" do
it "show a list of all users" do
get :index
expect(response).to be_success
end
end
If you really want to check rendering 如果您真的要检查渲染
describe "GET #index" do
render_views
it "show a list of all users" do
total = User.all.count
get :index
expect(response).to contain total.to_s
# OR
expect(response.body).to match total.to_s
end
end
see: https://www.relishapp.com/rspec/rspec-rails/v/2-2/docs/controller-specs/render-views 参见: https : //www.relishapp.com/rspec/rspec-rails/v/2-2/docs/controller-specs/render-views
If you want check displaying of some information on page, it will be better to write integrations test using Capybara. 如果要检查页面上某些信息的显示,最好使用Capybara编写集成测试。 Purpose of controller tests is to check incoming parameters, variables initialized in controller and controller response (rendering views or redirecting...).
控制器测试的目的是检查传入的参数,在控制器中初始化的变量以及控制器响应(呈现视图或重定向...)。 About your question - if you have next controller:
关于您的问题-如果您有下一个控制器:
class UsersController < ApplicationController
def index
@users = User.all
end
end
you can write next controller test: 您可以编写下一个控制器测试:
describe UsersController do
it "GET #index show a list of all users" do
User.create(email: 'aaa@gmail.com', name: 'Tim')
User.create(email: 'bbb@gmail.com', name: 'Tom')
get :index
expect(assigns[:users].size).to eq 2
end
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.