使用 RSpec 3 和 Rails 4 在控制器测试中查找新创建的记录 [英] Find a newly created record in a controller test using RSpec 3 and Rails 4

查看:38
本文介绍了使用 RSpec 3 和 Rails 4 在控制器测试中查找新创建的记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在 Rails 4 中制定控制器规范,我想测试由控制器操作创建的记录的属性.如何找到新创建的记录?

例如,我可以做什么来代替

它将新用户标记为待处理"做后:创建,参数# 我不想使用下面这行用户 = 用户.last期望(用户).to be_pending结尾

Rails 指南 仅简要介绍控制器测试,它提到测试 Article.count 改变 1,但没有提到如何获得新的 ActiveRecord 模型.

在 Rails 3 中查找最新记录的问题是关于导轨 3.

我不愿意使用 User.last,因为默认排序可能不是创建日期.

解决方案

在控制器测试中比较 recordsobjects 不是一个好主意.在控制器 create 测试中,您应该测试正确的重定向和记录的更改.

您可以在模型测试中轻松比较您的对象,因为您可以轻松跟踪您的记录.

不过,如果您的 action 有一个保存 recordvariable

,您可以从测试中访问创建的记录

在控制器中

 def 创建@user = #分配用户结尾

测试中

assigns(:user).name.should eq "Name" # 如果有name属性assigns(:user).pending.should be_true # 不知道你是怎么实现pending的

你可以看看这篇文章

I'm doing a controller spec in Rails 4, and I'm wanting to test the attributes of a record created by a controller action. How do I find the newly created record?

For example, what could I do instead of

it 'Marks a new user as pending' do
  post :create, params
  # I don't want to use the following line
  user = User.last
  expect(user).to be_pending
end

The Rails guides only briefly talks about controller tests, where it mentions testing that Article.count changes by 1, but not how to get a new ActiveRecord model.

The question Find the newest record in Rails 3 is about Rails 3.

I'm reluctant to use User.last, because the default sorting may be by something other than creation date.

解决方案

It is not a good idea to compare records or objects in controller tests. In a controller create test, you should test the correct redirection and the changing of the record.

You can easily compare your objects in a model test, because you can easily track your record.

Still, you can access the created record from a test if your action has a variable that holds the record like

In controller

 def create 
   @user = #assign user
 end

In Test

assigns(:user).name.should eq "Name" # If it has a name attribute
assigns(:user).pending.should be_true # I don't know how you implemented pending

You can take a look at this article

这篇关于使用 RSpec 3 和 Rails 4 在控制器测试中查找新创建的记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆