Find a newly created record in a controller test using RSpec 3 and Rails 4

丶灬走出姿态 提交于 2019-12-07 23:55:58

问题


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.


回答1:


If a controller has an instance variable named @user, then we can access it in RSpec by assigns(:user).




回答2:


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



来源:https://stackoverflow.com/questions/32731143/find-a-newly-created-record-in-a-controller-test-using-rspec-3-and-rails-4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!