Reputation: 4032
How do I write a spec to check if a new record is created in the database after a successful user signup? Using rspec in Rails 4 with capybara, factorygirl, and database_cleaner gems.
I feel like this situation is common and an answer should be easy to find, but I haven't been able to find one here or via google.
Upvotes: 29
Views: 30416
Reputation: 27747
You probably want the change matcher
You will do something like:
expect {
post :create, :user => {:user => :attributes }
}.to change { User.count }
or
expect {
post :create, :user => {:user => :attributes }
}.to change(User, :count)
This code says:
expect that running this first block of code to change the value I get when I run that block of code
and is functionally equivalent to writing:
before_count = User.count
post :create, :user => {:user => :attributes }
expect(User.count).not_to eq(before_count)
Upvotes: 51
Reputation: 125
As you are using factorygirl, you can used factorygirl to create test data
FactoryGirl.define do
factory :user do
sequence(:name) { |n| "user #{n}" }
sequence(:email) { |n| "sampleuser+#{n}@sampleuser.com" }
password '123456789'
end end
you can used 'FactoryGirl.create(:user)' whenever you want a user record.
To test you can write spec like this
expect{
post :create, {user: FactoryGirl.attributes_for(:user)}
}.to change(User, :count).by(1)
Upvotes: 6
Reputation: 42799
Since you mentioned capybara so I'm gonna assume you want a feature spec, of course you're going to need to change the details to match your application
require 'rails_helper'
feature 'Users' do # or whatever
scenario 'creating an account' do
visit root_path
click_link 'Sign Up'
fill_in 'Name', with: 'User 1'
fill_in 'Email', with: '[email protected]'
fill_in 'Password', with: 'password'
expect{
click_button 'Sign up'
}.to change(User, :count).by(1)
end
end
Upvotes: 12