4

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.

Community
  • 1
  • 1
Andrew Grimm
  • 78,473
  • 57
  • 200
  • 338

2 Answers2

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

Rokibul Hasan
  • 4,078
  • 2
  • 19
  • 30
  • I mean it for something like you can assign a `record` to a `variable`, then can operate with that `variable` eg. `let(:user) { Fabricate.build :user }` now `user` will be available in your example and you can operate `user` eg. `expect(user.disabled?).to be_true` – Rokibul Hasan Sep 23 '15 at 05:18
  • I've tried fixing the grammar of your answer. Did I inadvertently change any of the meaning? Also, with "and test the changing of the record", do you mean testing whether an individual record is changed, or testing whether the number of records has changed? – Andrew Grimm Sep 23 '15 at 06:05
  • thanks, sorry for my bad English, I have edit the line, I thinks I will be more understandable now :) – Rokibul Hasan Sep 23 '15 at 08:19
2

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

ahmacleod
  • 4,280
  • 19
  • 43
Johnny Dương
  • 753
  • 3
  • 8