LightBox
LightBox

Reputation: 3425

Can rspec save data to database?

Creating a user through a json post with httparty creates the user (as seen by the server logs) but the test fails on both conditions. Either user count is not changed or the user is not found. Is this a problem with my understanding of testing, the spec or the way rspec handles creating db records?

Results:

  1) User signup and signin with native request with valid information should save the user
     Failure/Error: User.where(email: "[email protected]").should exist
       expected #<ActiveRecord::Relation []> to exist

  1) User signup and signin with native request with valid information should save the user
     Failure/Error: expect {
       result should have been changed by 1, but was changed by 0

Spec:

describe "User", :type => :api do
  describe 'signup and signin' do 
  .
  .
   context "with native request" do
     context "with valid information" do
       it "should save the user" do 
        expect {
        response2 = HTTParty.post('http://localhost:3000/api/v1/registrations.json', 
        :body => { :user => 
          {
          :username => "bigbadwolf",
          :email => "[email protected]",
          :password => "mywolfie", 
          :password_confirmation => "mywolfie"
          } }.to_json,
       :headers => { 'Content-Type' => 'application/json', 'ClientType' => 'native', 'Accept' => 'application/json' })
       }.to change{User.count}.by(1) 
       User.where(email: "[email protected]").should exist
       .
       .
      end  
    end
    end
  end
end

Logs:

(2.0ms)  BEGIN
  User Exists (1.0ms)  SELECT 1 AS one FROM "users" WHERE LOWER("users"."email") = LOWER('[email protected]') LIMIT 1
  User Exists (1.0ms)  SELECT 1 AS one FROM "users" WHERE "users"."username" = 'bigbadwolf' LIMIT 1
  SQL (1.0ms)  INSERT INTO "users" ("created_at", "email", "password_digest", "updated_at", "username") VALUES ($1, $2, $3, $4, $5) RETURN
ING "id"  [["created_at", Tue, 25 Mar 2014 18:37:10 UTC +00:00], ["email", "[email protected]"], ["password_digest", "$2a$10$gGxQl6.W
O3.zb5EhPNL2A.m88vBIJ0DQ785PRjhxvorW4oDdYL4rC"], ["updated_at", Tue, 25 Mar 2014 18:37:10 UTC +00:00], ["username", "bigbadwolf"]]
   (1.0ms)  COMMIT
Completed 200 OK in 116ms (Views: 1.0ms | ActiveRecord: 11.0ms)

Upvotes: 1

Views: 1701

Answers (1)

LightBox
LightBox

Reputation: 3425

Rspec was saving data to the development database instead of test. I needed to configure for test mode.

Force rspec to use the test database.

# spec_helper.rb
ENV["RAILS_ENV"] = 'test'

Run the server in test mode.

rails s -e test

Upvotes: 1

Related Questions