Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a record is saved in the database using rspec with Rails 4?

Tags:

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.

like image 724
jeffhale Avatar asked May 11 '15 02:05

jeffhale


People also ask

Does RSpec clean database?

I use the database_cleaner gem to scrub my test database before each test runs, ensuring a clean slate and stable baseline every time. By default, RSpec will actually do this for you, running every test with a database transaction and then rolling back that transaction after it finishes.

What is let in RSpec?

let generates a method whose return value is memoized after the first call. This is known as lazy loading because the value is not loaded into memory until the method is called. Here is an example of how let is used within an RSpec test. let will generate a method called thing which returns a new instance of Thing .

What is describe in RSpec?

The word describe is an RSpec keyword. It is used to define an “Example Group”. You can think of an “Example Group” as a collection of tests. The describe keyword can take a class name and/or string argument.


1 Answers

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) 
like image 68
Taryn East Avatar answered Oct 05 '22 07:10

Taryn East