Disable rest-client output on minitest - ruby-on-rails

I've searched for this, but without success.
I have some tests (minitest) that use RestClient and Webmock. When passing for those tests I always have the request logged, polluting the test ouput:
[$] rake
Run options: --seed 60435
Running:
.........................................................RestClient.get "http://example.com/some_controller/some_action?userLocale=fr_FR", "Accept"=>"*/*", "Accept-Encoding"=>"gzip, deflate", "User-Agent"=>"rest-client/2.0.0 (darwin14.1.0 x86_64) ruby/2.2.1p85" # => 200 OK | 4 bytes
Is there a way to disable this ?
[EDIT]
Just to add, if I call the same address using ruby URL I have nothing logged (even using webmock) so it really is something related with Rest-client.
I already tried to set the ENV['RESTCLIENT_LOG'] variable, but without success.

What about:
RestClient.stub :log, '' do
# Your test code here
end
http://www.rubydoc.info/gems/minitest/4.2.0/Object:stub
You have many other options to redirect the log output:
In your test_helper.rb:
RestClient.log = 'tmp/test.log'
http://www.rubydoc.info/gems/rest-client/1.8.0/RestClient.log=
From the command line:
RESTCLIENT_LOG=tmp/restclient.log bundle exec rails test
In last resort you could monkey patch:
# test_helper.rb
RestClient.class_eval do
def self.log
''
end
end

Related

Heroku rake task with poltergeist

I'm writing a rake task which tests an application. To test it I need Capybara and Poltergeist.
Rake task looks like this:
require "capybara"
require "capybara/poltergeist"
require "capybara/dsl"
namespace :almet do
desc "Checking if something changed on tatar.ru"
task check_news: :environment do
Capybara.current_driver = :poltergeist
Browser = Class.new { include Capybara::DSL }
page = Browser.new.page
page.visit("http://almetyevsk.tatar.ru")
unless page.has_selector?(".home-events ul li") &
page.has_selector?(".home-events__item-lead") &
page.has_selector?(".home-events__item-date") &
page.has_selector?("h2 a")
then
alert
end
news_link = page.find(:css, "h2 a", match: :first)[:href]
page.visit(news_link)
unless page.has_selector?(".page__content-i h2") &
page.has_selector?(".page__content-i .news") &
page.has_selector?("i")
then
alert
end
end
def alert
AlertMailer.alert.deliver_now
end
end
This code checks if the main site from parsing data is still the same (no changes in css selectors). This rake task works good locally, but when I pushed it to heroku I've got an error:
rake aborted!
Cliver::Dependency::NotFound: Could not find an executable ["phantomjs"] on your path.
I googled this, installed phantomJS but still got the same error.(Poltergeist using phantomJS). Is it possible to solve my problem?
You need to install PhantomJS onto your Heroku instance. Usually that involves adding a build pack which will install it for you, like https://github.com/stomita/heroku-buildpack-phantomjs

RSpec is Freezing

I have rspec configured installed in my rails app. It was working fine (We are just experimenting with rspec so there's only 2 tests).
They were working fine. Now rspec is freezing when it's going to perform a test using database.
I just freezes. I don't even know were to start looking because there's no error in the output.
Is there a verbose or debugging mode for rspec or someone ever faced this?
I've tried -b but it freezes before can give an error.
Output: (Rspec is configured with --format documentation)
[leandro#machine:~] rspec
User
Than, that's it. It hangs. I has to reset manually the computer twice.
This is the user_spec.rb
require 'spec_helper'
describe User do
let(:user) { User.create({
username: "teste",
email: "teste#teste.com",
name: "Teste",
phone: "123456789",
password: "123456",
notes: "Teste"
}) }
subject { user }
it "is invalid without a username" do
user.username = nil
is_expected.not_to be_valid
end
end
And my spec_helper.rb
# This file is copied to spec/ when you run 'rails generate rspec:install'
ENV["RAILS_ENV"] ||= 'test'
require File.expand_path("../../config/environment", __FILE__)
require 'rspec/rails'
Dir[Rails.root.join("spec/support/**/*.rb")].each { |f| require f }
# Checks for pending migrations before tests are run.
ActiveRecord::Migration.maintain_test_schema!
RSpec.configure do |config|
config.infer_base_class_for_anonymous_controllers = false
config.order = "random"
config.color = true
config.tty = true
config.formatter = :documentation #:progress, :html, :textmate
config.expect_with :rspec do |c|
c.syntax = :expect
end
end
SOLUTION
It turns out that delayed_job_active_record gem was causing the hanging.
I don't know why, but as #Greg Malcolm I looked into the log/teste.log and rspec was feeezing right after createing the delayed jobs database and setting up a new user.
I've restricted the gem just for development and production enviroment, and it worked!
I haven't heard of a rake like verbose feature for rspec. But it's probably more useful to look through log/test.log and see what shows up there. It shows database activity which is part of a freeze effect.
You might also want to rails console into test and make sure your database connection is working right.
You have to check the ./log/test.log file. As this file tends to grow big, use the tail command to read the last n lines.
For example, to read the last 5 lines of the log file, execute the following command:
tail -5 ./log/test.log
In my case, my Google Pub/Sub emulator was hanging.
[ActiveJob] Failing with status #<struct Struct::Status code=4, details="Deadline Exceeded", metadata={}>
[ActiveJob] calling pubsub.googleapis.com:443:/google.pubsub.v1.Publisher/GetTopic
It might also be helpful to use tail -f ./log/test.log, to keep track of the logs while RSpec is running. You can read more about it on "Tail Your Test Logs", by thoughtbot.
It's pretty old question but in case anybody else will get this. I've got the same strange Rspec behaviour today because of left --drb option in project .rspec file after removing DRb server (spork or zeus). Just make sure Rspec have DRb disabled if you don't have spork or zeus installed.

Getting an error when running headless jasmine tests in rails

I've got a rake task set up to run headless jasmine tests on a build server and output the results in junit format. Here's the task:
namespace :jasmine do
desc "Runs Jasmine tests headlessly and writes out junit xml."
task :headless_junit do |t, args|
run_jasmine_tests(Dir.pwd)
end
end
def run_jasmine_tests(output_dir)
require 'headless'
require 'jasmine'
require 'rspec'
require 'rspec/core/rake_task'
output_file = "#{output_dir}/jasmine_results.xml"
Headless.ly do
RSpec::Core::RakeTask.new(:jasmine_continuous_integration_runner) do |t|
t.rspec_opts = ['--format', 'RspecJunitFormatter', '--out', output_file ]
t.verbose = true
t.rspec_opts += ["-r #{File.expand_path(File.join(::Rails.root, 'config', 'environment'))}"]
t.pattern = [Jasmine.runner_filepath]
end
Rake::Task['jasmine_continuous_integration_runner'].invoke
end
end
When I run the this I get this error:
TypeError: jasmine.getEnv(...).currentSpec is null in http://localhost:34002/assets/jquery.js?body=true (line 1129)
expect#http://localhost:34002/assets/jquery.js?body=true:1129
#http://localhost:34002/__spec__/activity_catalog_search_filters_spec.js:15
jasmine.Block.prototype.execute#http://localhost:34002/__jasmine__/jasmine.js:1064
jasmine.Queue.prototype.next_#http://localhost:34002/__jasmine__/jasmine.js:2096
jasmine.Queue.prototype.next_/onComplete/<#http://localhost:34002/__jasmine__/jasmine.js:2086
... LOTS MORE ...
I'm using rails 3.2.13, jasmine 1.3.2, headless 1.0.1, rspec 2.14.1 and Jasmine-jQuery 1.5.8
I think it could be similar to the problem this guy is having:
TypeError: jasmine.getEnv().currentSpec is null
Turns out the issue was with a test that was using jQuery.get to load a url into the dom. An empty string was being passed down as the url (since the test writer didn't really care what was loaded I guess) but that caused jQuery to fetch the current page (the jasmine tests themselves) and load that into the dom. Massive chaos ensued.
The more interesting thing (and perhaps more helpful) was how we figured that out. Turns out the fancy rake task was not the issue. It's just that the headless tests use Firefox and I usually load them manually in chrome, where this error didn't seem to happen. One I had the error reproduced in Firefox it was easy enough to track down the cause with the debugger.
So the bottom line is, if you're ci tests are failing and you can't reproduce it, try loading them manually in Firefox.

Autotest: "Could not run tests". But nothing in the log

Autotest broke with rspec-rails 2.2.1 update. Now I can't get it working again.. .even after rolling back to rspec-rais 2.2.0.
Only info I'm able to find is a Growl popup saying "App: Could not run tests". Nothing is being written to log/test.log.
this is output in console:
/Users/meltemi/.rvm/rubies/ruby-1.9.2-p0/bin/ruby -I.:lib:test -rubygems -e "%w[test/unit test/test_helper.rb].each { |f| require f }" | unit_diff -u
Loaded suite -e
Started
Finished in 0.003428 seconds.
0 tests, 0 assertions, 0 failures, 0 errors, 0 skips
Test run options: --seed 38767
Any ideas where to start troubleshooting this? I'd look in an autotest.log...if i could find one!?!
Edit: tried running autotest with autotest -v and get a looong list of "No tests matched..." in the console (20± examples below):
...
No tests matched .git/objects/fe/41f5cc24d667635c46a533fd09bf7bb514e032
No tests matched .git/objects/fe/4577696b2811818fe7439990be0d2f65a892c5
No tests matched .git/objects/fe/e16b09c5e782035a347ed9b257ff9b2b3fa173
No tests matched .git/refs/heads/MenuModel
No tests matched .git/refs/heads/master
No tests matched .git/refs/remotes/origin/master
No tests matched .git/refs/tags/v0.0.1
No tests matched .git/refs/tags/v0.0.1.1
No tests matched .gitignore
No tests matched .rspec
No tests matched Capfile
No tests matched Gemfile
No tests matched Gemfile.lock
No tests matched README
No tests matched Rakefile
No tests matched app/helpers/application_helper.rb
No tests matched autotest/discover.rb
No tests matched config/application.rb
No tests matched config/boot.rb
No tests matched config/database.yml
No tests matched config/deploy.rb
No tests matched config/environment.rb
...
here's the config (~/.autotest):
# ~/.autotest
# Include plugins
require 'autotest/fsevent'
require 'autotest/growl'
# ./.autotest
# exceptions (files to ignore)
# mappings (which files to specifically monitor for changes)
Autotest.add_hook(:initialize) {|at|
at.add_exception %r{^\.git} # ignore Version Control System
at.add_exception %r{^./tmp} # ignore temp files, lest autotest will run again, and again...
# at.clear_mappings # take out the default (test/test*rb)
at.add_mapping(%r{^lib/.*\.rb$}) {|f, _|
Dir['spec/**/*.rb']
}
nil
}
autotest -s rspec2 tells autotest to use the "rspec2" style, which will make it look for spec files and run the examples therein.
This is just a workaround though. Autotest is supposed to discover the specs based on the entries in your project's ./autotest/discover.rb. And as you found, a recent code update broke the autodiscovery. I ran into this myself and was unable to track down the source.

How can I tell if Rails code is being run via rake or script/generate?

I've got a plugin that is a bit heavy-weight. (Bullet, configured with Growl notifications.) I'd like to not enable it if I'm just running a rake task or a generator, since it's not useful in those situations. Is there any way to tell if that's the case?
It's as simple as that:
if $rails_rake_task
puts 'Guess what, I`m running from Rake'
else
puts 'No; this is not a Rake task'
end
Rails 4+
Instead of $rails_rake_task, use:
File.basename($0) == 'rake'
I like NickMervin's answer better, because it does not depend on the internal implementation of Rake (e.g. on Rake's global variable).
This is even better - no regexp needed
File.split($0).last == 'rake'
File.split() is needed, because somebody could start rake with it's full path, e.g.:
/usr/local/bin/rake taskname
$0 holds the current ruby program being run, so this should work:
$0 =~ /rake$/
It appears that running rake will define a global variable $rakefile, but in my case it gets set to nil; so you're better off just checking if $rakefile has been defined... seeing as __FILE__ and $FILENAME don't get defined to anything special.
$ cat test.rb
puts(global_variables.include? "$rakefile")
puts __FILE__
puts $FILENAME
$ cat Rakefile
task :default do
load 'test.rb'
end
$ ruby test.rb
false
test.rb
-
$ rake
(in /tmp)
true
./test.rb
-
Not sure about script/generator, though.
The most stable option is to add $is_rake = true at the beginning of Rakefile and use it from your code.
Use of $0 or $PROGRAM_NAME sometimes will fail, for example when using spring and checking variables from config/initializers
You can disable the plugin using environment variable:
$ DISABLE_BULLET= 1 rake some:task
And then in your code:
unless ENV['DISABLE_BULLET']
end
We could ask this
Rake.application.top_level_tasks
In a rails application, this is an empty array, whereas in a Rake task, the array has the task name in it.
top_level_tasks probably isn't a public API, so it's subject to changes. But this is the only thing I have found.

Resources