Fixtures for Apartment Gem - ruby-on-rails

I'm trying to do some tests with my multi-tenancy rails app but getting into trouble with my fixtures. In my controller test I have the following setup:
setup do
Apartment::Tenant.create('test')
Apartment::Tenant.switch! 'test'
host! "test:3000"
sign_in users(:admin)
end
When running the test I get this Error:
ActiveRecord::RecordNotFound: Couldn't find User with 'id'=255947101
I think the problem is that the fixtures are being created before switching to the test tenant. How do I create the fixtures after switching the tenant?

Ran into this same problem this morning ... I was able to get around it, at least for now, with this change in my test_helper.rb file:
# Customizing the base TestCase
module ActiveSupport
class TestCase
Apartment::Tenant.create('the-tenant')
Apartment::Tenant.switch! 'the-tenant'
fixtures :all
ActiveRecord::Migration.check_pending!
def setup
Capybara.app_host = 'http://www.my-somain.local'
DatabaseCleaner.strategy = :transaction
end
def teardown
Apartment::Tenant.drop('the-tenant')
Apartment::Tenant.reset
DatabaseCleaner.clean
end
end
end
Basically, I moved the tenant creation outside the setup method, where it previously resided. This seems to have fixed the issue with the fixtures being created outside the tenant on which I am testing.
I hope this helps ... not 100% sure it's ideal but it does have my tests running today :)

Related

Tell Rspec - don't delete my test_db when before running tests

I populate a database that I want to run rspec tests against.
Rspec seems to delete the db before it starts the tests. How can I tell Rspec not to delete this test_db?
I populate the db outside of Rails / Rspec environment. To build all the factories needed to build up the DB is just not practical for the scope of the project but I would like to test against existing DB.
You can manage clean your database using database cleaner gem, and The documentation recommends the following configuration for rspec as this link, but you change as the following:
RSpec.configure do |config|
config.before(:suite) do
DatabaseCleaner.strategy = :transaction
DatabaseCleaner.clean_with(:truncation)
end
end
But, I prefer to create your database in test environment before scenario, as example:
describe "specific name for this scenario" do
before do
#object = create(:object) # using factory girl as example
end
end
so, this data'll be generate for each time you run your test-case, read more about creating data for rspec-test.
I used the advice given in this question: Rspec don't delete 2 specific tables
In spec_helper.rb:
Commented out call to truncate_all_tables.
Then changed line:
config.use_transactional_fixtures = true
to
config.use_transactional_fixtures = false

Does rspec access the database when tests are run?

I'm using rspec-rails to test a controller in my rails application. In one instance, I'm creating new objects to test that they're properly assigned to instance variables.
describe MainController do
describe "GET #index" do
it "properly assigns a colored ball" do
ball1 = Ball.create(color: 'red')
get :index
expect(assigns(:red_balls)).to eq([ball1])
end
end
end
When I run the test, does rspec access the database to create ball1 and then delete it once the test is run?
From the snippet in your question, Yes Rspec access the DB configured as test in the database.yml file, if you want to clean out the DB/Records created by Rspec you can use the database_cleaner gem you can configure it as you deem fit.
e.g:
add gem database_cleaner to your Gemfile
and the below to your spec_helper.rb file as specified by the database_cleaner documentation:
RSpec.configure do |config|
config.before(:suite) do
DatabaseCleaner.strategy = :transaction
DatabaseCleaner.clean_with(:truncation)
end
config.before(:each) do
DatabaseCleaner.start
end
config.after(:each) do
DatabaseCleaner.clean
end
end
Then database_cleaner would truncate the tables in the test db and leave them in a pristine state
To add to what bjhaid said above - Rspec should only be accessing you 'test' database. Check out the config/database.yml to see the configuration of your different databases.
So you do not have to worry about things in your development or production databases interfering with your testing database.
Yes, RSpec allows your database calls to go through, but with the rspec-rails gem under the default configuration, it will execute each test within a database transaction and will roll back that transaction at the end of each example with no action required on your part. No additional gem is required. See https://relishapp.com/rspec/rspec-rails/docs/transactions.

RSpec leaves record in test database

Whenever I run a user test, RSpec leaves the Fabricated user in the test database after the test has completed, which is messing up my other tests. I will do a rake db:test:prepare, but when I run my tests again, the record is recreated in my database. I have no idea why this is happening. It only happens with user objects.
In my spec_helper file I even have:
config.use_transactional_fixtures = true
Here is an example test that creates a record:
it "creates a password reset token for the user" do
alice = Fabricate(:user)
post :create, email: alice.email
expect(assigns(alice.password_reset_token)).to_not eq(nil)
end
Fabricator:
Fabricator(:user) do
email { Faker::Internet.email }
password 'password'
name { Faker::Name.name }
end
Could this have anything to do with my users model?
you should use a gem called database_cleaner that will truncate your database and reset everything automatically so in your gem file add the gem database_cleaner after that inside your spec_helper.rb configure it
spec_helper.rb
config.use_transactional_fixtures = false
config.before(:suite) do
DatabaseCleaner.strategy = :truncation
end
config.before(:each) do
DatabaseCleaner.start
end
config.after(:each) do
DatabaseCleaner.clean
end
and then create a new file in your spec/support directory
spec/support/shared_db_connection.rb
class ActiveRecord::Base
mattr_accessor :shared_connection
##shared_connection = nil
def self.connection
##shared_connection || retrieve_connection
end
end
ActiveRecord::Base.shared_connection=ActiveRecord::Base.connection
Now whenever you run your tests the database will be reset.This was taken from the book 'Everyday Rails testing with RSpec' by Aaron Sumner
Each test is wrapped in a database transaction. That means that everything created during the test should be gone when the test finishes. Therefore, I would suspect that whatever you have in your database was made outside the test itself (like in a before(:all) block).
Also this doesn't guarantee that your database will be empty each time you run your tests. It might be possible that you accidentally added a record somehow, and now it just keeps reverting to that state.
If you want to make sure your tests have a shiny database each time, you should have a look at the database_cleaner gem.
The simplest solution is to make sure RSpec tests run in transactions (Rails does this by default)
spec_helper.rb
config.around(:each) do |example|
ActiveRecord::Base.transaction do
example.run
raise ActiveRecord::Rollback
end
end
If I had to guess, the line post :create, email: alice.email seems like a likely candidate for doing the actual user creation.
Stub that line out with an bogus test and see if you're still getting a user created in the DB.
My problem turned out to be that I was was using before(:all) in my RSpec files which I found out the hard way that the data created does not get rolled back. I switched to before(:example) per this article: https://relishapp.com/rspec/rspec-rails/docs/transactions

authlogic not working with capybara when using the selenium driver

I have all my capybara tests working with my authlogic members area using the default driver, but when i change one test to use selenium driver as it has ajax in it, it gives my theis error :
You must activate the Authlogic::Session::Base.controller with a controller object before creating objects
Things are working with default driver for authlogic so must be something to do with selenium ??
I have include Authlogic::TestCase in my spec_helper and
activate_authlogic
domain.user_sessions.create(user)
in a before each.
Any one help me with this please ?
thanks rick
I posted a cucumber solution here: Log-in through authlogic without having to fill in form every time
For RSpec integration tests it's similar.
In your spec_helper.rb:
require "authlogic/test_case"
RSpec.configure do |config|
...
config.include Authlogic::TestCase
ApplicationController.skip_before_filter :activate_authlogic
config.before(:each, :type => :request) do
activate_authlogic
UserSession.create(User.find_by_email!(email))
end
...
end
Obviously, if your site is not login only you may want to move the two lines in config.before into a before block in your specific test for logged in specs. If you leave as is you can delete the session with UserSession.find.destroy or obviously follow the logout link (if this makes more sense in your spec).
I think the following code will work to activate authlogic:
Authlogic::Session::Base.controller = Authlogic::ControllerAdapters::RailsAdapter.new(self)
Having said that, I prefer defining a step that actually goes to the login form, fills it out, and logs in. It's slower, but I rarely run my entire integration test suite manually, usually the continuous integration server takes care of that.
This work for me (Rails 3.2.1) :
In spec_helper.rb
require 'authlogic/test_case'
include Authlogic::TestCase
In In my controller_specs :
def valid_session
activate_authlogic # run before tests are executed
user = Factory(:user)
UserSession.create(user, true) #create an authlogic session
#user = #controller.current_user
{}
end
# exemple of valid_session utilization in your test:
# valid_session
# user_id = #user.id
#
# or
#
# get :index, {}, valid_session
Enjoy!

rails test database won't wipe

I'm running rails 3.0.3 and using rspec-rails 2.4.1 with a postgresql database. Whenever I run my RSpec tests, the data remains at the end. Does anyone know how to get rails or rspec to wipe the test environment's data between each use?
Please tell me if there's any further information that could make answering my question easier.
Thanks!Tristan
Install the database_cleaner gem and then add this to your spec_helper.rb.
Spec::Runner.configure do |config|
config.before(:suite) do
DatabaseCleaner.strategy = :transaction
DatabaseCleaner.clean_with(:truncation)
end
config.before(:each) do
DatabaseCleaner.start
end
config.after(:each) do
DatabaseCleaner.clean
end
end
Use transactional examples to rollback the data after every test run
RSpec.configure do |config|
config.use_transactional_examples = true
end
You don't need any extra gem in order to clean your test DB between runs. In your spec_helper.rb file, configure rspec as follows:
RSpec.configure do |c|
c.around(:each) do |example|
ActiveRecord::Base.connection.transaction do
example.run
raise ActiveRecord::Rollback
end
end
end
Another possibility, that I just put myself through, is using the wrong before block.
I accidentally set a before block as an all instead of an each:
before :all do
user = FactoryGirl.create(:user)
sign_in user
end
This caused the user to stick around in the database for the entire rspec run, which caused validation collisions.
Instead, the before should be an each so that everything is kept clean through the rspec run:
before :each do
user = FactoryGirl.create(:user)
sign_in user
end
If you've made this mistake, then you will probably need to manually clean up your test database before things go back to normal. The simplest way to do that is probably to truncate each of the tables (aside from schema_migrations).

Resources