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.
If a controller has an instance variable named @user
, then we can access it in RSpec by assigns(:user)
.
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