0

If I run the below spec by running rspec spec/controllers/brands_controller_spec.rb the last test fails giving me the PG error that the user is not in the database. BUT if I run the tests individually they all pass, so it doesn't seem like my tests are messed up, just something I'm missing with rspec?

I create an activity everytime they user is updated, which is triggered when a user is created and logs in (Devise keeps track of sign in dates etc.) which creates an activity. When my test logs in the admin user it tries to create this activity with the association with the admin user, the error is saying that even though I signed in the user I'm violating a PG rule because the user is not in the database...even though it is? Very confused.

Brands Controller Spec

describe 'GET #index' do

    context 'unauthenticated_user' do
        it "blocks an unauthenticated_user from getting to the index page" do
            get :index
            expect(response).to redirect_to new_user_session_path
        end
    end

    context 'authenticated_user NOT admin' do

        it "redirects non admin employees" do
            login_user
            get :index
            expect(response).to redirect_to @user
        end
    end

    context 'authenticated_user admin' do

        it "renders the index template for the authenticated_user" do
            login_admin
            get :index
            expect(response).to render_template :index
        end
    end                 
end

spec/support/controller_macros.rb

module ControllerMacros
  def login_user
      @request.env["devise.mapping"] = Devise.mappings[:user]
      @user = FactoryGirl.create(:user)
      sign_in @user
  end

  def login_admin
      @request.env["devise.mapping"] = Devise.mappings[:user]
      @admin_user = FactoryGirl.create(:admin)
      sign_in @admin_user
  end
end

Error:

1) BrandsController GET #index authenticated_user admin renders the index template for the authenticated_user
     Failure/Error: Activity.create(user_id: user_id, trackable_id: self.id, trackable_type: self.class.name, action: "#{self.class.name} #{self.id} #{self.full_name} created")


 ActiveRecord::InvalidForeignKey:
   PG::ForeignKeyViolation: ERROR:  insert or update on table "activities" violates foreign key constraint "fk_rails_7e11bb717f"
   DETAIL:  Key (user_id)=(2185) is not present in table "users".
   : INSERT INTO "activities" ("user_id", "trackable_id", "trackable_type", "action", "created_at", "updated_at") VALUES ($1, $2, $3, $4, $5, $6) RETURNING "id"
 # ./app/models/user.rb:691:in `record_create'
 # ./spec/support/controller_macros.rb:10:in `login_admin'
 # ./spec/controllers/brands_controller_spec.rb:26:in `block (4 levels) in <top (required)>'
 # ------------------
 # --- Caused by: ---
 # PG::ForeignKeyViolation:
 #   ERROR:  insert or update on table "activities" violates foreign key constraint "fk_rails_7e11bb717f"
 #   DETAIL:  Key (user_id)=(2185) is not present in table "users".
 #   ./app/models/user.rb:691:in `record_create'

Edit: Adding another error I found using Pry inside the test.

It appears it's something with PG preventing the user creation going through in the 2nd test to actually create the user.

ActiveRecord::StatementInvalid: 
  PG::InFailedSqlTransaction: ERROR:      
    current transaction is aborted, commands ignored until end of   transaction block
    : SELECT  "users".* FROM "users"  ORDER BY "users"."id" ASC LIMIT 1

Edit Adding in database cleaner stuffs:

  config.before(:suite) do
    DatabaseCleaner.strategy = :transaction
    DatabaseCleaner.clean_with :truncation
  end

  config.around(:each) do |example|
    DatabaseCleaner.cleaning do
     example.run
    end
 end

 config.after(:each) do
   DatabaseCleaner.clean
 end
Steve Q
  • 395
  • 5
  • 28
  • Just to be sure, the factory for `user` and `admin` works?. Check if the user created is valid. – Andrés Nov 26 '16 at 23:54
  • yup, that works. They are valid and both work if I run the test individually which is really weird. It's only when I try to run all the tests in the file that they fail. – Steve Q Nov 27 '16 at 00:03
  • Are you using some database cleaner and a `before_save` callback to track the activity (user created)? – Andrés Nov 27 '16 at 00:08
  • I'm using an after_create, after_update, and after_destroy to track the activities at the Model level. I'm using database_cleaner. I just added that configuration to the question to give more clarity. Something I"m missing there? – Steve Q Nov 27 '16 at 00:25
  • maybe this can helps you, I'm note sure: http://stackoverflow.com/questions/2979369/databaseerror-current-transaction-is-aborted-commands-ignored-until-end-of-tra – Andrés Nov 27 '16 at 00:50
  • It's not rails, but it't related. You need to check what is causing the error in pg and try to fix that first. The error is on 2, not on 3 I think. 2 fails, databasecleaner try to do rollback and does not work, then 3 fails – Andrés Nov 27 '16 at 00:52
  • I think it's more of a databasecleaner configuration problem. I tried the RSpec with Capybara Example https://github.com/DatabaseCleaner/database_cleaner but that's not working either. They explain the same problem I'm having but their setup isn't working for me. – Steve Q Nov 27 '16 at 00:58
  • Yes, maybe. Try changing the strategy to `:truncation` for example – Andrés Nov 27 '16 at 01:04
  • how about that. That did the trick! Can you put that as an answer so I can accept it? – Steve Q Nov 27 '16 at 01:07

1 Answers1

1

Try changing the strategy to :truncation.

Andrés
  • 624
  • 7
  • 12