Record persisting past test in Rails3 - ruby-on-rails-3

I'm working through the railstutorial.org site and seem to have a problem with an integration test. It's suppose to check if a user gets properly created after a form post which works but, on subsequent tests fails because the test db is not getting rolled backed, this causes error because of validating that users can't have same email. Any explanation why the record would persist? If relevant the code in question is from this listing.

Note: I am the author of the Rails Tutorial. The config.cache_classes = false line got added after Peter Cooper reported that it was necessary to get RSpec and Spork to work together on his system. Since I have not found it necessary, and since it seemed to introduce lots of problems (such as those identified in this thread), that line has since been removed. If you use the latest version of the book you shouldn't run into this problem.

Look into using database_cleaner. Your spec helper will contain something like this:
config.before(:suite) do
DatabaseCleaner.strategy = :transaction
DatabaseCleaner.clean_with :truncation
end
config.before(:each) do
ActionMailer::Base.deliveries = []
DatabaseCleaner.start
end
config.after(:each) do
DatabaseCleaner.clean
end
config.after(:all) do
DatabaseCleaner.clean_with :truncation
end

Seems that the issue was with the line
config.cache_classes = false
I had set this to false assuming it would make sure not to use stale class data, but it seems to be having the opposite effect among other things. Changing this to true fixed all the weirdness I was having, but I am still on confused as to why. I think it may have something to do with the OS as in the tutorial it was said that for OSX (which I am running) having that line set to true works fine, while other OSes need it set false

While Hartl's tutorial struck me as flawless, perhaps the issue you raise here can be classified as an important ommission.
This here: RailsTutorial - chapter 8.4.3 - Test database not clearing after adding user in integration test
and
This here: Rails 3 Tutorial Chapter 11 "Validation failed: Email has already been taken" error
and
This here: config.cache_classes = false messing up rspec tests?
... are all variations on the same problem.
Mike Hartl, if you are out there, you seem a mere one issue away from RoR Tutorial perfection.
Best regards,
Perry

Related

How to clean DB with Rails 5, Minitest, Capybara JS (Selenium)?

I have set up a very simple rails 5 project to narrow down my problem:
https://github.com/benedikt-voigt/capybara_js_demo
In this project the data mutation done by the Capybara JS is not deleted, neither by Rails nor by the Database cleaner I added.
The following great blog argues, that no DatabaseCleaner is needed:
http://brandonhilkert.com/blog/7-reasons-why-im-sticking-with-minitest-and-fixtures-in-rails
but this works only for fixtures, not for the mutation done by an out-of-thread Capybara test.
I added the Database cleaner, but this also needed work.
Does anybody has a sample setup?
From a quick look at your test I would say it's leaving data because the data is actually being added after DatabaseCleaner cleans. The click_on call occurs asynchronously, so when your assert_no_content call happens there's no guarantee the app has handled the request yet or the page has changed yet and since the current page doesn't have the text 'Name has already been taken' on it the assertion passes and the database gets cleaned. While that is happening the click gets processed by the app and the new data is created after the cleaning has occurred. You need to check/wait for content that will appear on the page after the click - something like
page.assert_text('New Foo Created')
You should only be asserting there is no content once you already know the page has changed, or you're expecting something to disappear from the current page.
I solved now the problem by setting the DB connection to one
class ActiveRecord::Base
mattr_accessor :shared_connection
##shared_connection = nil
def self.connection
##shared_connection || ConnectionPool::Wrapper.new(:size => 1) { retrieve_connection }
end
end
ActiveRecord::Base.shared_connection = ActiveRecord::Base.connection
as describe here:
https://mattbrictson.com/minitest-and-rails
I uploaded the working repo here:
https://github.com/benedikt-voigt/capybara_js_demo_working

Database Cleaner Not Cleaning One Cucumber Scenario

So my team is driving out our rails app (a survey and lite electronic record system) using Cucumber, Rspec and all the gems necessary to use these testing frameworks. I am in the process of setting up a Jenkins CI server and wanted to standardize our databases across our testing, development, and staging environments (we ended up choosing MySQL).
Upon switching the testing environment from SQlite to MySQL we discovered a couple of caching-related testing bugs that we resolved by using relative ids instead of hard-coded ones. example:
describe "#instance_method" do
before(:each) do
#survey = FactoryGirl.create(:survey)
#question_1 = FactoryGirl.create(:question)
#question_2 = FactoryGirl.create(:question)
....
end
context "question has no requirements" do
it "should match" do
# below breaks under MySQL (and postgres), but not SQlite
expect { #survey.present_question?(2) }.to be_true
# always works
expect { #survey.present_question?(#question_2.id) }.to be_true
end
end
end
After resolving this one failing spec, I addressed some unrelated ajax issues that have forever plaguing our test suite. Thinking that I finally masted the art of testing, I confidently ran rake. I was met with this unfriendly sight:
Now of course cucumber features/presenting_default_questions.feature rains green when ran in isolation.
Failing Scenario:
#javascript
Feature: Dynamic Presentation of Questions
In order to only answer questions that are relevant considering previously answered questions
As a patient
I want to not be presented questions that illogical given my previously answered question on the survey
Scenario: Answering a question that does not depend on any other questions
Given I have the following questions:
| prompt | datatype | options | parent_id | requirement |
| Do you like cars? | bool | | | |
| Do you like fruit? | bool | | | |
When I visit the patient sign in page
And I fill out the form with the name "Jim Dog", date of birth "1978-03-30", and gender "male"
And I accept the waiver
Then I should see the question "Do you like cars"
When I respond to the boolean question with "Yes"
Then I should see the question "Do you like fruit?"
When I respond to the boolean question with "No"
Given I wait for the ajax request to finish
Then I should be on the results page
Relevant step:
Then(/^I should be on the results page$/) do
# fails under ``rake`` passes when run in isolation
current_path.should == results_survey_path(1)
end
Then(/^I should be on the results page$/) do
# passes in isolation and under ``rake``
current_path.should == results_survey_path(Survey.last.id)
end
Besides from using Capybara.javascript_driver = :webkit, the cucumber / database cleaner config is unmodified from rails g cucumber:install.
It seems like both the failing rspec and cucumber tests suffer from the same sort of indexing problem. While the solution proposed above works, it's super janky and begs the question as to why a simple absolute index doesn't work (after all the database is cleaned between each scenario and feature). Is there something up with my tests? With database_cleaner?
Please let me know if more code would be helpful!
Relavent gem versions:
activemodel (3.2.14)
cucumber (1.3.6)
cucumber-rails (1.3.1)
database_cleaner (1.0.1)
capybara (2.1.0)
capybara-webkit (1.0.0)
mysql2 (0.3.13)
rspec (2.13.0)
The problem seems to be that you are missing the database_cleaner code for your Cucumber scenarios.
You mentioned that you have the database_cleaner code for your RSpec scenarios, but it seems that you're missing something like this for Cucumber's env.rb:
begin
require 'database_cleaner'
require 'database_cleaner/cucumber'
DatabaseCleaner.strategy = :truncation
rescue NameError
raise "You need to add database_cleaner to your Gemfile (in the :test group) if you wish to use it."
end
Around do |scenario, block|
DatabaseCleaner.cleaning(&block)
end
Do you have this code in there?

Rails2 update_without_callbacks monkeypatch

I know monkey patches are bad, but I have the following patch for update_without_callbacks for my Rails2 app, but I am having a hard time porting it to rails3 as that method no longer exists in Rails3.
Here is the definition:
def update_without_callbacks(attribute_names = #attributes.keys)
if changed?
update_creating_new_version_row(attribute_names)
update_shared_columns
else
Rails.logger.info("this record unchanged; skipping update")
end
true
end
Please suggest as to how i should go about porting it to Rails3. Thanks.
It should be replaced by:
save(:callbacks => false)

Disable Rails SQL logging in console

Is there a way to disable SQL query logging when I'm executing commands in the console? Ideally, it would be great if I can just disable it and re-enable it with a command in the console.
I'm trying to debug something and using "puts" to print out some relevant data. However, the sql query output is making it hard to read.
Edit:
I found another solution, since setting the logger to nil sometimes raised an error, if something other than my code tried to call logger.warn
Instead of setting the logger to nil you can set the level of the logger to 1.
ActiveRecord::Base.logger.level = 1 # or Logger::INFO
To turn it off:
old_logger = ActiveRecord::Base.logger
ActiveRecord::Base.logger = nil
To turn it back on:
ActiveRecord::Base.logger = old_logger
This might not be a suitable solution for the console, but Rails has a method for this problem: Logger#silence
ActiveRecord::Base.logger.silence do
# the stuff you want to be silenced
end
Here's a variation I consider somewhat cleaner, that still allows potential other logging from AR. In config/environments/development.rb :
config.after_initialize do
ActiveRecord::Base.logger = Rails.logger.clone
ActiveRecord::Base.logger.level = Logger::INFO
end
For Rails 4 you can put the following in an environment file:
# /config/environments/development.rb
config.active_record.logger = nil
In case someone wants to actually knock out SQL statement logging (without changing logging level, and while keeping the logging from their AR models):
The line that writes to the log (in Rails 3.2.16, anyway) is the call to debug in lib/active_record/log_subscriber.rb:50.
That debug method is defined by ActiveSupport::LogSubscriber.
So we can knock out the logging by overwriting it like so:
module ActiveSupport
class LogSubscriber
def debug(*args, &block)
end
end
end
I used this: config.log_level = :info
edit-in config/environments/performance.rb
Working great for me, rejecting SQL output, and show only rendering and important info.
In Rails 3.2 I'm doing something like this in config/environment/development.rb:
module MyApp
class Application < Rails::Application
console do
ActiveRecord::Base.logger = Logger.new( Rails.root.join("log", "development.log") )
end
end
end
Just as an FYI, in Rails 2 you can do
ActiveRecord::Base.silence { <code you don't want to log goes here> }
Obviously the curly braces could be replaced with a do end block if you wanted.
I use activerecord 6.0.3.3 and I had to include ActiveSupport::LoggerSilence
include ActiveSupport::LoggerSilence
ActiveSupport::LoggerSilence.silence do
## everything you want to silence
end
This however did not work with anything related to creating or deleting SQL tables like ActiveRecord::Migration.drop_table. For this to be silenced I added:
ActiveRecord::Schema.verbose = false
I had to solve this for ActiveRecord 6, and I based my answer on fakeleft's response, but it wasn't quite right, since it was suppressing other logging such as the logging of nested views. What I did was created config/initializers/activerecord_logger.rb:
# Suppress SQL statement logging if necessary
# This is a dirty, dirty trick, but it works:
if ENV["ACTIVERECORD_HIDE_SQL"].present?
module ActiveRecord
class LogSubscriber
def sql(event)
end
end
end
end
The log subscriber in AR 6 has a sql event that we want to hide, so this is very narrowly targeted to skip that event.

uninitialized constant Twitter::OAuth

I'm struggling to get my app to display a timeline of feeds from my app. So far I've used the oauth-plugin, oauth and twitter gems (for rails3) to get it authorised. This has worked just fine.
Now I'm struggling when I try and connect.
I end up with an error:
uninitialized constant Twitter::OAuth
Have checked I don't have another action calling twitter (as in another post here). But so far, no luck.
Hope someone can help!
Edit -
I forgot to mention I'm using Devise to authenticate my users. Have tried inserting:
require 'twitter'
But still no success..
-- EDIT TWO --
Found a solution on the twitter gem git site about depreciating this in version 1.0.
I've now replaced the code in my twitter_token.rb file with:
def client
unless #client
#twitter_oauth=Twitter::Client.new(:TwitterToken.consumer.key,:TwitterToken.consumer.secret)
#twitter_oauth.authorize_from_access(token,secret)
#client=Twitter::Base.new(#twitter_oauth)
end
Which gets rid of that error but now leads to another :(
undefined method `consumer' for :TwitterToken:Symbol
I have also tried this:
def client
unless #client
#twitter_oauth=Twitter::Client.new(:oauth_token =>'TwitterToken.consumer.key', :oauth_token_secret=>'TwitterToken.consumer.secret')
#twitter_oauth.authorize_from_access token,secret
#client=Twitter::Base.new(#twitter_oauth)
end
Which gives the following error:
undefined method `authorize_from_access' for #<Twitter::Client:0x00000102da1530>
Any ideas? I'm going insane!
I'm going to answer my own question here - if it helps one person, it's worth it considering I lost three days to it.
Using the latest twitter gem, devise and oauth-plugin. I was seeing a lot of errors. The latest twitter_token controller on the oauth-plugin site does not work, even though it's been updated for a recent twitter gem..
In the end, I deleted my entire twitter_token.rb file and started again:
require 'twitter'
class TwitterToken < ConsumerToken
TWITTER_SETTINGS={:site=>"http://api.twitter.com", :request_endpoint => 'http://api.twitter.com',}
def self.consumer
#consumer||=OAuth::Consumer.new credentials[:key],credentials[:secret],TWITTER_SETTINGS
end
def client
Twitter.configure do |config|
config.consumer_key = TwitterToken.consumer.key
config.consumer_secret = TwitterToken.consumer.secret
config.oauth_token = token
config.oauth_token_secret = secret
end
#client ||= Twitter::Client.new
end
end
You can then update twitter using something like this:
<%= current_user.twitter_token.client.update("At last it's working!") %>
Also, make sure you're using the rails3 branch of the oauth-plugin..