进行控制器测试并希望测试当我进入索引页面时,我应该看到创建的用户总数应该等于实际创建的所有用户。不能让它工作,没有错误出现,它只是冻结,我必须按控制c退出。
describe "GET #index" do
it "show a list of all users" do
total = User.all.count
get :index
expect(response).to eq total
end
答案 0 :(得分:1)
rspec控制器测试默认情况下不渲染视图,测试成功可能是更好的开始
describe "GET #index" do
it "show a list of all users" do
get :index
expect(response).to be_success
end
end
如果你真的想检查渲染
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
请参阅:https://www.relishapp.com/rspec/rspec-rails/v/2-2/docs/controller-specs/render-views
答案 1 :(得分:0)
如果要在页面上检查显示某些信息,最好使用Capybara编写集成测试。 控制器测试的目的是检查传入的参数,在控制器中初始化的变量和控制器响应(渲染视图或重定向......)。 关于你的问题 - 如果你有下一个控制器:
class UsersController < ApplicationController
def index
@users = User.all
end
end
你可以写下一个控制器测试:
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