Recaptcha with devise is not working on ruby on rails? - ruby-on-rails-3

I get this error:
There has been an unexpected error with the application. Please contact the administrator. error code: success
I am using recaptcha with devise, I edited where appropriate as stated by following the steps mentioned on this page
Here is my Gemfile:
source 'https://rubygems.org'
gem 'rails', '3.2.8'
gem 'json'
gem 'execjs'
gem 'therubyracer'
gem 'will_paginate', "3.0.pre4"
group :production do
gem 'pg'
end
group :assets do
gem 'sass-rails', '~> 3.2.3'
gem 'coffee-rails', '~> 3.2.1'
gem 'uglifier', '>= 1.0.3'
gem 'jquery-fileupload-rails'
gem "letter_opener"
gem 'jquery-ui-rails'
end
gem 'jquery-rails'
gem "carrierwave"
gem "fastercsv"
gem 'devise', '2.1.2'
gem 'rmagick'
gem 'mailman', :require=> false
gem 'activeadmin'
gem 'kaminari'
gem 'prawn'
gem 'recaptcha', :require => 'recaptcha/rails'

I hope you have followed it exactly what it says on the documentation For instance, to support recaptcha on ruby 1.8.X and 1.9.X, there are different line of code. However, after a short research I found out this website you can use recaptcha without the plugins regardless of your rails version. I hope this helps. :)

From Recaptcha Site (almost).... I'm in Rails 4 with Devise (aparently the hard bundle).. No, is too easy. Procedure apply to any ruby, any rails, and devise (or without devise). Tested in ruby/rails/devise 1.9.3/3.2.x/2.2.1 & 2.0.x/4.0.x/3.2.4 and last one without Devise.
Edit next files:
Gemfile
gem 'ruby-recaptcha'
# bundle install
config/initializers/credentials.rb (any file in this path it's ok)
# Set constants
RCC_PUB = "your_public_key"
RCC_PRIV= "your_private_key"
# re-start server. Try to keep safety this data using ENV vars.
app/views/devise/registrations/new.html.erb (or form you prefer)
# form
<%= simple_form_for(resource, as: resource_name, :url => registration_path(resource_name) do |f| %>
<%= f.input :email, autofocus: true, required: true %>
...
<!-- Add next line -->
<div id="captchadiv"></div>
<%= f.button :submit, "Register", class: 'btn btn-danger' %>
<% end %
At the end of same file (can be in awesome_funcs.js.erb file)
<script type="text/javascript" charset="utf-8">
$(function () {
function showRecaptcha() {
Recaptcha.create("<%= RCC_PUB %>", "captchadiv", {
theme: "white",
lang: 'en'
});
};
showRecaptcha();
});
</script>
And the little trick, app/controllers/application_controller.rb
# On top
include ReCaptcha::AppHelper
before_action :configure_permitted_parameters, if: :devise_controller?
# If already you have this method or any other with before_filter
# Into method
protected
def configure_permitted_parameters
if controller_name == "registrations" && action_name == "create"
# Rails 3: If you prefer, put this into registrations#create method
unless validate_recap(params, User.new.errors) # Or your model
# wrong input is handled here
flash[:error] = "Text from images doesn't match with your input"
redirect_to :back # or other stuff
# As my submit is with Ajax, I do a render instead redirect:
# render :json => {other: "recaptcha_failed"}
# In success callback I evaluate response and Recaptcha.reload() paints a new recaptcha.
end
end
....
# trick: do everything before params sanitizers
end
As we are using Ajax plugin, finally, add in
app/views/layouts/application.html.erb
(just before end of body)
<body>
...
...
<script type="text/javascript" src="http://www.google.com/recaptcha/api/js/recaptcha_ajax.js"></script>
</body>
That's it. You have recaptcha
Advice:
If you use Ajax to do submit, you can use success callback for a Recaptcha.reload() in case images and input doesn't match.
Other, if your form is "remote: true", you can use above behavior after "create" method in create.js.erb file in your views directory.
IMPORTANT: In some projects when form arrives from a link Recaptcha doesn't appear. Try to locate the launcher link into a div or in a parent div add "data-no-turbolink". I had this issue in Rails 4.

Related

Rails get random yoda giphy API image to show on 'welcome/yoda'

I got the translate yoda API to work from mashape. https://github.com/sfinley89/BEWD_midcourse
Now Im trying to get random yoda giphy images to show up on the 'welcome/yoda' page when their text is translated into yoda speak.
Here is what im getting right now showing on the 'welcome/yoda'
Yoda Says, "Lets gets some gifs alrady. "
#<Giphy::RandomGif:0x007ffae5467e08>
#<unirest::httpresponse:0x007ffae57a23e8>
{"data"=>{"type"=>"gif", "id"=>"PciMitIKp0UjS", "url"=>"http://giphy.com/gifs/yoda-PciMitIKp0UjS", "image_original_url"=>"http://media4.giphy.com/media/PciMitIKp0UjS/giphy.gif", "image_url"=>"http://media4.giphy.com/media/PciMitIKp0UjS/giphy.gif", "image_mp4_url"=>"http://media4.giphy.com/media/PciMitIKp0UjS/giphy.mp4", "image_frames"=>"21", "image_width"=>"150", "image_height"=>"190", "fixed_height_downsampled_url"=>"http://media4.giphy.com/media/PciMitIKp0UjS/200_d.gif", "fixed_height_downsampled_width"=>"158", "fixed_height_downsampled_height"=>"200", "fixed_width_downsampled_url"=>"http://media4.giphy.com/media/PciMitIKp0UjS/200w_d.gif", "fixed_width_downsampled_width"=>"200", "fixed_width_downsampled_height"=>"253", "fixed_height_small_url"=>"http://media4.giphy.com/media/PciMitIKp0UjS/100.gif", "fixed_height_small_still_url"=>"http://media4.giphy.com/media/PciMitIKp0UjS/100_s.gif", "fixed_height_small_width"=>"79", "fixed_height_small_height"=>"100", "fixed_width_small_url"=>"http://media4.giphy.com/media/PciMitIKp0UjS/100w.gif", "fixed_width_small_still_url"=>"http://media4.giphy.com/media/PciMitIKp0UjS/100w_s.gif", "fixed_width_small_width"=>"100", "fixed_width_small_height"=>"127", "username"=>"", "caption"=>""}, "meta"=>{"status"=>200, "msg"=>"OK"}}
Back
How do I get this to show the random yoda gif?
Here is my controller welcome_controller.rb
class WelcomeController < ApplicationController
def index
#ask
end
def ask
end
def yoda
##voice = HTTParty.get('https://yoda.p.mashape.com/yoda?sentence=You+will+learn+how+to+speak+like+me+someday.++Oh+wait.').parsed_response
#sentence = "You+will+learn+how+to+speak+like+me+someday.++Oh+wait."
sentence = params[:sentence]
#render plain: ENV["YODA_KEY"]
#response = Unirest.get "https://yoda.p.mashape.com/yoda?sentence="+sentence,
headers:{
"X-Mashape-Key" => ENV["YODA_KEY"],
"Accept" => "text/plain",
}
#gifpic = Unirest.get "http://api.giphy.com/v1/gifs/search?q=Yoda&api_key=dc6zaTOxFJmzC"
#gif = Giphy.random('Yoda')
url = "http://api.giphy.com/v1/gifs/random?api_key=dc6zaTOxFJmzC&tag=yoda"
resp = Net::HTTP.get_response(URI.parse(url))
buffer = resp.body
#result = JSON.parse(buffer)
end
end
Here is my welcome/index.html.erb
<center>
<h2>Midcourse Project</h2><br>
<br>
<%= link_to "Ask Yoda How He Would Say It!", 'welcome/ask' %>
<br><br><br><br><br><br>
<%= image_tag "http://www.extension.zone/wp-content/uploads/2015/05/Giphy-logo.jpg", size: "200x100", :alt => 'logo' %>
</center>
Here is welcome/ask.html.erb
<center>
<h1> I am yoda! What do you want me to say? </h1><br>
<%= form_tag "/welcome/yoda" %>
<%= text_field_tag :sentence %>
<%= submit_tag "Submit" %>
</center>
Here is welcome/yoda.html.erb
<p> Yoda Says, "<%= p #response.raw_body %>"</p> <br>
<%= #gif %> <br>
<%= image_tag #gifpic %> <br>
<%= p #result %>
<br>
<%= link_to "Back", '/welcome/ask' %>
Here is my gemfile
source 'https://rubygems.org'
# unirest http://unirest.io/ruby
gem 'unirest', '~> 1.1', '>= 1.1.2'
# HTTParty
#gem 'httparty', '~> 0.13.7'
# Gem from https://rubygems.org/gems/giphy/versions/3.0.0
# gifs https://github.com/sebasoga/giphy
gem 'giphy', '~> 3.0'
# Geocoding https://github.com/alexreisner/geocoder
gem 'geocoder'
# Yelp https://github.com/Yelp/yelp-ruby
gem 'yelp', require: 'yelp'
# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '4.2.3'
# Use postgresql as the database for Active Record
gem 'pg'
# Use SCSS for stylesheets
gem 'sass-rails', '~> 5.0'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'
# Use CoffeeScript for .coffee assets and views
gem 'coffee-rails', '~> 4.1.0'
# See https://github.com/rails/execjs#readme for more supported runtimes
# gem 'therubyracer', platforms: :ruby
# Use jquery as the JavaScript library
gem 'jquery-rails'
# Turbolinks makes following links in your web application faster. Read more: https://github.com/rails/turbolinks
gem 'turbolinks'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.0'
# bundle exec rake doc:rails generates the API under doc/api.
gem 'sdoc', '~> 0.4.0', group: :doc
# Use ActiveModel has_secure_password
# gem 'bcrypt', '~> 3.1.7'
# Use Unicorn as the app server
# gem 'unicorn'
# Use Capistrano for deployment
# gem 'capistrano-rails', group: :development
group :development, :test do
# Call 'byebug' anywhere in the code to stop execution and get a debugger console
gem 'byebug'
# Access an IRB console on exception pages or by using <%= console %> in views
gem 'web-console', '~> 2.0'
# Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
gem 'spring'
end
And here is the routes.rb
Rails.application.routes.draw do
# get the yoda page
get 'welcome/yoda'
# post to the yoda page
post 'welcome/yoda'
# get the ask page
get 'welcome/ask'
# The priority is based upon order of creation: first created -> highest priority.
# See how all your routes lay out with "rake routes".
# You can have the root of your site routed with "root"
root 'welcome#index'
end
Documentation:
on github checkout /Giphy/GiphyAPI
or /sebasoga/giphy
Please help me out with this.
Answer: <%= image_tag #result["data"]["image_url"] %> put this in your views where you want it displayed.
Change controller welcome_controller.rb to look like
class WelcomeController < ApplicationController
def index
#ask
end
def ask
end
def yoda
##voice = HTTParty.get('https://yoda.p.mashape.com/yoda?sentence=You+will+learn+how+to+speak+like+me+someday.++Oh+wait.').parsed_response
#sentence = "You+will+learn+how+to+speak+like+me+someday.++Oh+wait."
sentence = params[:sentence]
#render plain: ENV["YODA_KEY"]
#response = Unirest.get "https://yoda.p.mashape.com/yoda?sentence="+sentence,
headers:{
"X-Mashape-Key" => ENV["YODA_KEY"],
"Accept" => "text/plain",
}
url = "http://api.giphy.com/v1/gifs/random?api_key=dc6zaTOxFJmzC&tag=yoda"
resp = Net::HTTP.get_response(URI.parse(url))
buffer = resp.body
#result = JSON.parse(buffer)
end
end
Change view welcome/yoda.html.erb to look like
<p> Yoda Says, "<%= p #response.raw_body %>"</p> <br>
<%= image_tag #result["data"]["image_url"] %>
<br>
<%= link_to "Back", '/welcome/ask' %>

Devise : undefined method `user_signed_in? Didn't know why?

Please help i am using rails 3.2.11 and devise 2.0.6 but when i am trying to run my project i am getting an error undefined method `user_signed_in?' for Class
i have done lot of google but didnt find any solution.!
Below is my application trace
NoMethodError in Home#index
Showing /home/amits/RailsWorkspace/Myapp/app/views/home/index.html.haml where line #3 raised:
undefined method `user_signed_in?' for #<#<Class:0xbb1f3f4>:0xbae60b8>
Extracted source (around line #3):
1: %h2= (t :welcome) + " Myapp"
2:
3: - if user_signed_in?
4: = link_to (I18n.t :customers), user_root_path
5: / %li
6: / = link_to (I18n.t :sign_out), destroy_user_session_path, :method => :delete
Rails.root: /home/amits/RailsWorkspace/Myapp
Application Trace | Framework Trace | Full Trace
app/views/home/index.html.haml:3:in `_app_views_home_index_html_haml___806580830_97751900'
Request
Parameters:
None
Show session dump
Show env dump
Response
Headers:
None
and my gem file is as follows
Gemfile :
source 'https://rubygems.org'
gem 'rails', '3.2.11'
gem 'heroku'
gem 'pg'
gem 'haml'
gem 'haml-rails', :group => :development
gem 'rmagick'
group :assets do
gem 'sass-rails', '~> 3.2.3'
gem 'coffee-rails', '~> 3.2.0'
gem 'uglifier', '>= 1.0.3'
end
gem "devise", "~> 2.0.0"
gem 'devise_aes_encryptable'
# version added so that the gem version will be stable at this point.
gem 'geokit', '1.5.0'
gem 'geokit-rails3', '0.1.5'
My Home controller
Homescontroller.rb
class HomeController < ApplicationController
before_filter :authenticate_user!
def index
end
end
My user model
User.rb
class User < ActiveRecord::Base
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable, :token_authenticatable, :omniauthable
# Setup accessible (or protected) attributes for your model
attr_accessible :email, :password, :password_confirmation, :remember_me, :sign_in_count
end
Rotes.rb
Myapp::Application.routes.draw do
devise_for :users
root to: "home#index"
end
Please help me....
Try removing 'clear_helpers' method in ApplicationController as it might block sometimes Devise to load his helpers.

CarrierWave not working with Fog -> ArgumentError ( is not a recognized storage provider): app/controllers/notes_controller.rb:11:in `create'

I followed the railscasts about using carrierwave with fog with aws s3 to the T but it doesnt seem to work.
The Gemfile is as follows:
source 'https://rubygems.org'
ruby '1.9.3'
gem 'rails', '3.2.13'
# Bundle edge Rails instead:
# gem 'rails', :git => 'git://github.com/rails/rails.git'
gem 'pg'
gem 'pg_search'
gem 'devise'
gem "therubyracer"
gem "less-rails" #Sprockets (what Rails 3.1 uses for its asset pipeline) supports LESS
gem "twitter-bootstrap-rails", :git => 'git://github.com/seyhunak/twitter-bootstrap-rails.git'
gem "simple_form"
gem 'aws-sdk', '~> 1.8.1.2'
gem 'activerecord-reputation-system', require: 'reputation_system'
gem 'bootstrap-will_paginate'
gem 'carrierwave'
gem "rmagick"
gem "fog", "~> 1.3.1"
gem 'carrierwave-aws'
config/initializers/carrierwave.rb
require 'carrierwave'
CarrierWave.configure do |config|
config.fog_credentials = {
provider: "AWS",
aws_access_key_id: ENV["xxx"],
aws_secret_access_key: ENV["yyy"],
region: ENV['ap-southeast-1']
}
config.cache_dir = "#{Rails.root}/tmp/uploads"
config.fog_directory = ENV["ABC"]
end
The uploader:
class ImageUploader < CarrierWave::Uploader::Base
require 'carrierwave/processing/mime_types'
before :store, :remember_cache_id
after :store, :delete_tmp_dir
# Include RMagick or MiniMagick support:
include CarrierWave::RMagick
# include CarrierWave::MiniMagick
# Include the Sprockets helpers for Rails 3.1+ asset pipeline compatibility:
include Sprockets::Helpers::RailsHelper
include Sprockets::Helpers::IsolatedHelper
# Choose what kind of storage to use for this uploader:
# storage :file
storage :fog
include CarrierWave::MimeTypes
process :set_content_type
# Override the directory where uploaded files will be stored.
# This is a sensible default for uploaders that are meant to be mounted:
def store_dir
"uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
end
version :thumb do
process :resize_to_limit => [200, 200]
end
# store! nil's the cache_id after it finishes so we need to remember it for deletion
def remember_cache_id(new_file)
#cache_id_was = cache_id
end
def delete_tmp_dir(new_file)
# make sure we don't delete other things accidentally by checking the name pattern
if #cache_id_was.present? && #cache_id_was =~ /\A[\d]{8}\-[\d]{4}\-[\d]+\-[\d]{4}\z/
FileUtils.rm_rf(File.join(root, cache_dir, #cache_id_was))
end
end
end
the controller:
class NotesController < ApplicationController
before_filter :authenticate_user!, only: [:create, :destroy]
before_filter :correct_user, only: :destroy
def index
end
def create
#note = current_user.notes.build(params[:note])
#notes = Note.paginate(page: params[:page])
if #note.save
flash[:success] = "Note uploaded!"
redirect_to root_url
else
flash.now[:error] = "Note failed to upload."
render 'static_pages/home'
end
end
def destroy
#note.destroy
flash[:success] = "Note deleted."
redirect_to root_url
end
private
def correct_user
#note = current_user.notes.find_by_id(params[:id])
redirect_to root_url if #note.nil?
end
end
I don't really know if the problem lies in the gem or the controller. Even the controller is based on the microposts controller in Michael Hartl's book "The Ruby on Rails Tutorial" so I don't know where I have gone wrong.
That's an awfully early version of fog. The latest is 1.12.1. Try updating to the latest release using the following entry in your Gemfile
gem "fog", "~> 1.12.1"

Authlogic / Selenium breaks after rails 3.2.12 upgrade

I'm using Authlogic and having difficulty getting my Selenium tests to work with :js=>true after upgrading to Rails 3.2.12. The same tests use to worked under Rails 3.1.3. I am running my tests using Spork.
I am logging in through Selenium launches Firefox (19.0.2), fills the login form but then I get a permissions error from Authlogic, the standard "You are not allowed to access this action."
I can see that many people are having issues with this but as I mentioned, has only became a problem for me once upgrading from Rails 3.1.3 to Rails 3.2.12. I suspect that the issue may be within my spec_helper file (below) and in particularly within the
module Authlogic
block which I got from here:
Authlogic with Capybara + Cucumber + Selenium Driver not working
**spec_helper.rb**
require 'rubygems'
require 'spork'
require 'authlogic/test_case'
include Authlogic::TestCase
Spork.prefork do
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}
RSpec.configure do |config|
config.color_enabled = true
ApplicationController.skip_before_filter :activate_authlogic
config.before(:each, :type => :request) do
activate_authlogic
end
config.include FactoryGirl::Syntax::Methods
config.include Capybara::DSL
config.use_transactional_fixtures = false
config.before(:suite) do
DatabaseCleaner.clean_with(:truncation)
end
config.before(:each) do
DatabaseCleaner.strategy = :transaction
end
config.before(:each, :js => true) do
Capybara.current_driver = :selenium
DatabaseCleaner.strategy = :truncation
module Authlogic
module Session
module Activation
module ClassMethods
def controller
if !Thread.current[:authlogic_controller]
Thread.current[:authlogic_controller] = Authlogic::TestCase::MockController.new
end
Thread.current[:authlogic_controller]
end
end
end
end
end
end
config.before(:each) do
DatabaseCleaner.start
end
config.after(:each) do
DatabaseCleaner.clean
end
config.include(MailerMacros)
config.before(:each) { reset_email }
config.mock_with :mocha
config.infer_base_class_for_anonymous_controllers = false
config.order = "random"
config.treat_symbols_as_metadata_keys_with_true_values = true
config.filter_run :focus => true
config.run_all_when_everything_filtered = true
end
end
Spork.each_run do
FactoryGirl.reload
end
My understanding is that Authlogic and Selenium Webdriver work on different threads hence the need for this patch in the spec_helper file.
In the Request Spec I get a permissions error from Authlogic. Here is the Request Spec test in question:
# UNIT REQUEST SPEC
require 'spec_helper'
describe "Units" do
describe "GET /admin/units/new" do
before(:each) do
activate_authlogic
UserSession.create FactoryGirl.create(:admin_user, :email => "foo#bar.com", :password => "password", :password_confirmation => "password")
visit root_path
fill_in "user_session[email]", :with => "foo#bar.com"
fill_in "user_session[password]", :with => "password"
click_button "Sign In"
end
it "displays a pop up dialog after unit is created", :focus, :js => true do
visit new_admin_unit_path
fill_in "Title", :with => "Unit Title"
fill_in "Code", :with => "U-TEST"
fill_in "Learning Outcome", :with => "Some Learning Outcome"
fill_in "unit[learning_outcomes_attributes][0][assessment_methods_attributes][0][content]", :with => "Some Assessment Criteria"
click_button "Save and Publish"
page.should have_css('div.ui-dialog')
end
end
end
My Capybara tests are working ok with:
activate_authlogic
UserSession.create FactoryGirl.build(:user)
in the before(:each) block, the problem only arises when using :js=>true
So, my questions are:
Is it a case that with Rails 3.2.x that the spec_helper fix (module Authlogic ... ) no longer works.
If that is in fact the case, what is the "normal" way of getting this to work?
Just revisited this today. When I upgraded Rails I also upgraded capybara to the latest version (2.1.0). It seems that downgrading capybara from this version (2.1.0) to version 2.0.1 seemed to do the trick. I can see that capybara (2.0.1) uses xpath (1.0.0) while capybara (2.1.0) uses xpath (2.0.0) along with a different version of nokogiri gem. I have no idea if there is a link there but here is my gem file if anyone cares to take a look:
source 'http://rubygems.org'
gem 'rails', '3.2.12'
gem 'rack-mini-profiler'
gem 'authlogic'
gem 'rails3-generators'
gem 'mysql2'
gem 'declarative_authorization'
gem 'kaminari'
gem "foreigner"
gem 'validates_timeliness'
gem "activerecord-import", ">= 0.2.0"
gem 'ezcrypto'
gem 'thin'
gem 'exception_notification'
gem 'mail'
gem 'libv8', '~> 3.11.8.0'
gem "therubyracer", :require => 'v8'
gem 'jasmine', :group => [:development, :test]
gem 'sprockets'
gem 'jquery-rails'
gem 'tinymce-rails'
gem 'acts_as_list'
gem 'cocaine'
gem 'rmagick'
gem 'carrierwave'
gem 'remotipart'
gem 'deep_cloneable', '~> 1.4.0'
gem 'delayed_job_active_record'
gem 'daemons'
gem 'rb-readline'
gem "jquery-migrate-rails", "~> 1.0.0"
gem 'ransack'
# Gems used only for assets and not required
# in production environments by default.
group :assets do
gem 'sass-rails', "~> 3.2.3"
gem 'coffee-rails', "~> 3.2.1"
gem 'uglifier', '>= 1.0.3'
end
# Bundle gems for the local environment. Make sure to
# put test-only gems in this group so their generators
# and rake tasks are available in development mode:
group :development, :test do
gem 'cheat'
gem 'ruby-growl'
gem 'letter_opener'
gem 'rspec-rails', "~> 2.0"
gem 'database_cleaner'
gem 'rb-fsevent', '~> 0.9.1'
gem 'guard-rspec'
gem 'spork-rails'
gem 'guard-spork'
gem 'factory_girl_rails'
gem 'capybara', '2.0.1'
gem 'launchy'
gem 'mocha', :require => false
gem 'better_errors'
gem 'binding_of_caller'
gem 'meta_request'
end

With Minitest+Guard+Spork, all test suites and support files are being reloaded on each run

I'm running into a problem where everything in my test setup, including Spork's prefork block, is being reloaded and invoked on each run. It is taking 5-8 seconds for a test to fire off after guard picks up a change even though this is a new project so there are minimal tests and I even have an SSD.
Before I realized everything was reloading, I profiled it using the technique described by Jo Liss here and I've included those hanging requires but obviously that didn't help since it's all being reloaded anyway. However, that's when I noticed this:
Loaded Suite
test,test/controllers,test/controllers/manage,test/factories,test/functional/manage,test/helpers,test/helpers/manage,test/integration,test/models,test/support
I'm not seeing why it would reload everything. This is my first attempt at setting up minitest+spork+guard (i should have just gone with rspec, sigh) so I'm hoping it's something stupid. I'm including everything in hopes that someone has run into it or can easily spot what I've missed. Thanks in advance!
My files include:
test_helper.rb
require 'spork'
Spork.prefork do
#MiniTest::Rails.override_testunit!
ENV["RAILS_ENV"] = "test"
require File.expand_path('../../config/environment', __FILE__)
require 'guard'
require 'guard/interactors/readline'
require 'guard/ui'
require 'guard/interactors/coolline'
require 'guard/interactor'
require 'guard/dsl'
require 'guard/notifiers/rb_notifu'
require 'guard/notifier'
require 'guard/minitest/notifier'
require 'guard/minitest/runners/default_runner'
Dir[File.expand_path('test/support/*.rb')].each { |file| require file }
require "mocha"
Spork.trap_method(Rails::Application, :reload_routes!)
Spork.trap_method(Rails::Application::RoutesReloader, :reload!)
end
Guardfile
guard 'bundler' do
watch('Gemfile')
# Uncomment next line if Gemfile contain `gemspec' command
# watch(/^.+\.gemspec/)
end
guard 'spork', :wait => 65, :test_unit => false, :minitest => true, :minitest_env => { 'RAILS_ENV' => 'test' }, :bundler => true do
watch('config/application.rb')
watch('config/environment.rb')
watch(%r{^config/environments/.+\.rb$})
watch(%r{^config/initializers/.+\.rb$})
watch('Gemfile')
watch('Gemfile.lock')
watch('test/test_helper.rb') { "test" }
end
guard 'minitest' do
watch(%r|^test/test_helper\.rb|) { "test" }
watch(%r|^test/support/(.*)\.rb|) { "test" }
watch(%r{^test/.+_test\.rb$})
watch(%r|^app/models/(.*)\.rb|) {|m| ["test/models/#{m[1]}_test.rb", "test/integration/#{m[1]}_test.rb"] }
watch(%r|^app/controllers/(.*)\.rb|) {|m| ["test/controllers/#{m[1]}_test.rb", "test/integration/#{m[1]}_test.rb"] }
watch(%r|^app/views/(.*)\.html|) {|m| "test/integration/#{m[1]}_test.rb" }
watch(%r|^app/objects/(.*)\.rb|) {|m| "test/objects/#{m[1]}_object_test.rb" }
end
guard 'livereload' do
watch(%r{app/.+\.(erb|haml)})
watch(%r{app/helpers/.+\.rb})
watch(%r{(public/|app/assets).+\.(css|js|html)})
watch(%r{(app/assets/.+\.css)\.scss}) { |m| m[1] }
watch(%r{(app/assets/.+\.js)\.coffee}) { |m| m[1] }
watch(%r{config/locales/.+\.yml})
end
support/minitest.rb
#require "minitest/autorun"
require "minitest/rails"
require "minitest/spec"
require "minitest/pride"
require "minitest/rails/shoulda"
require "minitest/autorun"
require "capybara/rails"
class RequestSpec < MiniTest::Spec
include Rails.application.routes.url_helpers
include Capybara::DSL
include Rails.application.routes.url_helpers
end
MiniTest::Spec.register_spec_type /integration$/i, RequestSpec
#MiniTest::Spec.register_spec_type /object$/, MiniTest::Spec
class MiniTest::Rails::Controller
include Devise::TestHelpers
end
support/turn.rb
require 'turn'
require 'turn/autorun'
require 'turn/colorize'
require 'turn/reporter'
require 'turn/reporters/pretty_reporter'
Turn.config do |c|
c.natural = true
c.ansi = true
c.format = :pretty
end
Gemfile
source 'https://rubygems.org'
# core
gem 'rails', '3.2.8'
gem 'thin'
# infrastructure
gem 'heroku'
gem 'foreman', :groups => [:development, :test]
# application monitoring
gem 'airbrake'
gem 'newrelic_rpm'
# view engine
gem 'haml', '>= 3.1.7'
gem 'haml-rails', '>= 0.3.5'
gem 'redcarpet' # markdown
# data persistence
gem 'mongoid', '>= 3.0.5'
gem 'redis'
gem 'redis-store'
gem 'redis-rails'
# email
gem 'sendgrid'
gem 'mailcatcher', :group => [:development]
# authentication and authorization
gem 'devise', '>= 2.1.2'
gem 'omniauth', '>= 1.0'
#gem 'authority'
gem 'cancan'
gem 'rolify', '>= 3.2.0'
# view helpers
gem 'bootstrap-generators', '~> 2.1', :group => [:development]
gem 'jquery-rails'
gem 'simple_form', '>= 2.0.2'
gem 'rails3-jquery-autocomplete'
# file attachments
gem 'rmagick'
gem 'fog'
gem 'carrierwave'
gem 'carrierwave-mongoid', :require => 'carrierwave/mongoid'
# url helpers
gem 'mongoid_slug'
# console tools
gem 'ansi', :groups => [:development, :test]
gem 'rack-livereload', :groups => [:development]
gem 'pry-rails', :groups => [:development]
gem 'growl', :groups => [:development, :test]
gem 'turn', :groups => [:test]
gem 'awesome_print'
gem 'progress_bar', :groups => [:test]
# supporting libraries
gem 'bson_ext'
gem 'nokogiri', :group => :test
gem 'ruby_parser', '>= 2.3.1', :group => :test
gem 'rb-fsevent', '~> 0.9.1', :group => :development
# assets
gem 'less-rails', :group => :assets
gem 'therubyracer', '>= 0.10.2', :group => :assets
gem 'uglifier', '>= 1.0.3', :group => :assets
# guard
gem 'guard', :group => :development
gem 'guard-livereload', :group => :development
gem 'guard-spork', :group => :development
gem 'guard-minitest', :group => :development
gem 'guard-bundler', :group => :development
# minitest
gem 'spork-minitest', :group => :test
gem 'minitest-rails', :group => :test
gem 'minitest-rails-shoulda', :group => :test, :git => 'git://github.com/rawongithub/minitest-rails-shoulda.git'
gem 'capybara_minitest_spec', :group => :test
# mocking
gem 'mocha', :group => :test
# http testing
gem 'vcr', :group => :test
gem 'webmock', :group => :test
# factories
gem 'factory_girl_rails'
It appears that Spork and Minitest were actually not working as expected. In order to fix this, the following changes had to be made:
Inside of the Guardfile, :drb => true had to be added to minitest:
guard 'minitest', :drb => true do
#...
end
However that alone will break guard/minitest/spork because it tries to force feed it the -r -e options which are not currently supported. You'll run into the following error:
Running: test/models/business_test.rb
Running tests with args ["-r", "/Users/chance/.rbenv/versions/1.9.3-p125/lib/ruby/gems/1.9.1/gems/guard-minitest-0.5.0/lib/guard/minitest/runners/default_runner.rb", "-e", "::GUARD_NOTIFY=true", "test/test_helper.rb", "./test/models/business_test.rb"]...
Exception encountered: #<LoadError: cannot load such file -- -r>
backtrace:
/Users/chance/.rbenv/versions/1.9.3-p125/lib/ruby/gems/1.9.1/gems/activesupport-3.2.8/lib/active_support/dependencies.rb:251:in `require'
/Users/chance/.rbenv/versions/1.9.3-p125/lib/ruby/gems/1.9.1/gems/activesupport-3.2.8/lib/active_support/dependencies.rb:251:in `block in require'
/Users/chance/.rbenv/versions/1.9.3-p125/lib/ruby/gems/1.9.1/gems/activesupport-3.2.8/lib/active_support/dependencies.rb:236:in `load_dependency'
/Users/chance/.rbenv/versions/1.9.3-p125/lib/ruby/gems/1.9.1/gems/activesupport-3.2.8/lib/active_support/dependencies.rb:251:in `require'
/Users/chance/.rbenv/versions/1.9.3-p125/lib/ruby/gems/1.9.1/gems/spork-minitest-0.0.3/lib/spork/test_framework/minitest.rb:13:in `block in run_tests'
/Users/chance/.rbenv/versions/1.9.3-p125/lib/ruby/gems/1.9.1/gems/spork-minitest-0.0.3/lib/spork/test_framework/minitest.rb:12:in `each'
/Users/chance/.rbenv/versions/1.9.3-p125/lib/ruby/gems/1.9.1/gems/spork-minitest-0.0.3/lib/spork/test_framework/minitest.rb:12:in `run_tests'
/Users/chance/.rbenv/versions/1.9.3-p125/lib/ruby/gems/1.9.1/gems/spork-0.9.2/lib/spork/run_strategy/forking.rb:13:in `block in run'
/Users/chance/.rbenv/versions/1.9.3-p125/lib/ruby/gems/1.9.1/gems/spork-0.9.2/lib/spork/forker.rb:21:in `block in initialize'
/Users/chance/.rbenv/versions/1.9.3-p125/lib/ruby/gems/1.9.1/gems/spork-0.9.2/lib/spork/forker.rb:18:in `fork'
/Users/chance/.rbenv/versions/1.9.3-p125/lib/ruby/gems/1.9.1/gems/spork-0.9.2/lib/spork/forker.rb:18:in `initialize'
/Users/chance/.rbenv/versions/1.9.3-p125/lib/ruby/gems/1.9.1/gems/spork-0.9.2/lib/spork/run_strategy/forking.rb:9:in `new'
/Users/chance/.rbenv/versions/1.9.3-p125/lib/ruby/gems/1.9.1/gems/spork-0.9.2/lib/spork/run_strategy/forking.rb:9:in `run'
/Users/chance/.rbenv/versions/1.9.3-p125/lib/ruby/gems/1.9.1/gems/spork-0.9.2/lib/spork/server.rb:48:in `run'
/Users/chance/.rbenv/versions/1.9.3-p125/lib/ruby/1.9.1/drb/drb.rb:1548:in `perform_without_block'
/Users/chance/.rbenv/versions/1.9.3-p125/lib/ruby/1.9.1/drb/drb.rb:1508:in `perform'
/Users/chance/.rbenv/versions/1.9.3-p125/lib/ruby/1.9.1/drb/drb.rb:1586:in `block (2 levels) in main_loop'
/Users/chance/.rbenv/versions/1.9.3-p125/lib/ruby/1.9.1/drb/drb.rb:1582:in `loop'
/Users/chance/.rbenv/versions/1.9.3-p125/lib/ruby/1.9.1/drb/drb.rb:1582:in `block in main_loop'
Done.
Fortunately, there is a pull request for spork-minitest that fixes it.
Once the gem was pointed over to the repo, it took a nice cut out of the load times. It isn't anywhere near as fast as node.js and mocha, but it is at least faster than rspec.