集成测试:`assert_select’a ‘`对于分页页面失败

我有很多集成测试,看起来像:

first_page_of_users = User.page(1) # Using kaminari for pagination. first_page_of_users.each do |user| assert_select 'a[href=?]', user_path(user) end 

这些测试失败并显示错误消息,例如:

 Expected at least 1 element matching "a[href="/users/1"]", found 0.. 

我将puts @response.body添加到测试中,以查看它响应的代码。

对于响应正文中包含的所有用户,它具有正确的href,例如href="/users/75938613" 。 但是, /users/后面的数字要高得多,并且“users1”确实不存在(不仅仅是url不存在,而且整个记录不在该页面上)。 如果我确保只有几个固定装置,以便不适用分页,则测试通过。 这让我觉得好像有了分页, first_page_of_users = User.page(1)应用的顺序与first_page_of_users.each do |user|的顺序不同first_page_of_users.each do |user| assert_select 'a[href=?]', user_path(user)期望…

可能导致此错误的原因是什么? 它适用于我的应用程序的不同页面和模型。


更新:对于另一个模型,即使我尝试

 Organization.all.each do |org| puts @response.body assert_select 'a[href=?]', organization_path(org) end 

我收到错误:

 Expected at least 1 element matching "a[href="/organizations/fix0"]", 

名称为“fix0”的组织根本不存在于它所响应的正文中。 我的(缩短的)固定装置在下面,他们确认不应该有任何具有该名称的组织。 知道发生了什么事吗?

 one: name: abcd activated: true activated_at: 2015-04-16 11:38:53 two: name: efgh activated: true activated_at: 2015-04-16 11:38:53  organization_: name:  activated: true activated_at:   

在进行集成测试时,重要的是要跟踪应该显示在哪里并进行测试。 因为在这种情况下我们有第一页的记录太多,所以落在后面的页面上的任何内容都将导致测试失败。 正如您所怀疑的那样,这样的事情应该validation结果的第一页是否存在:

 Organization.order('organizations.name','desc').page(1).each do |organization| assert_select 'a[href=?]', organization_path(organization) end 

我建议保留一个较小的数据集进行测试,因为在这种情况下,您还应该在测试中“获取”第二页并对“page(2)”执行上面的断言。 这意味着此集成测试必须发出两个get请求(以及您可能需要的任何设置)并检查结果,并养成这种习惯可能会降低您的套件速度。