CanCan uninitialized constant Ability::CanCan - cancan

Any idea what I could be doing wrong here? I know it's not very useful to say ability.can? :manage, all; however I'm just trying to get started with CanCan.
I do have the gem, and have run generate cancan:ability.
Thanks.
Error and Code:
uninitialized constant Ability::CanCan
Extracted source (around line #4):
1:
2: <% if current_user %>
3: <p>Currently logged in as <strong><%= current_user.email %></strong></p>
4: <% current_ability = Ability.new(current_user) %>
5: <%if can? :manage, :all %>
6: <p>Hey Buddy, You're Authorized ;)</p>
7: <% end %>

I received this error because my Gemfile placed the CanCan requirement in a group that was not being loaded in the test environment.
Try checking to see that your CanCan requirement is loaded in the environment you're running. This requirement will load CanCan in the default group:
# project_root/Gemfile
source 'http://rubygems.org'
gem 'rails', '3.1.0'
gem 'cancan'

Related

Remove markup in tests

When I run tests which fail I get a huge output with a lot of markup hiding the error.
Example:
$ perl script/my_prove.pl t/2410-topinfo.t
t/2410-topinfo.t .. 1/?
# Failed test '200 OK'
# at t/2410-topinfo.t line 12.
# got: '500'
# expected: '200'
# Failed test 'similar match for selector "h1"'
# at t/2410-topinfo.t line 12.
# ''
# doesn't match '(?^:Flatinfo\ Business\-Apartment\ Hietzing)'
# Failed test 'content is similar'
# at t/2410-topinfo.t line 12.
# '<!DOCTYPE html>
# <html>
# <head>
# <title>Server error (development mode)</title>
# <meta http-equiv="Pragma" content="no-cache">
# <meta http-equiv="Expires" content="-1">
# <script src="/mojo/jquery/jquery.js"></script>
# <script src="/mojo/prettify/run_prettify.js"></script>
# <link href="/mojo/prettify/prettify-mojo-dark.css" rel="stylesheet">
# <style>
# a img { border: 0 }
# body {
#
# ........... lots of lines removed here ...........
#
# <div id="wrapperlicious">
# <div id="nothing" class="box spaced"></div>
# <div id="showcase" class="box code spaced">
# <pre id="error">Can't call method "name" on an undefined value at template extern/topinfo/show.html.ep line 2.
# </pre>
#
# .... lots of lines follow here ............
The error seems to be a single line:
Can't call method "name" on an undefined value at template extern/topinfo/show.html.ep line 2
The test-script producing this output is:
use Mojo::Base -strict;
use Test::More;
use Test::Mojo;
use FindBin;
require "$FindBin::Bin/../script/ba_db";
my $t = Test::Mojo->new( 'BaDb' );
$t->ua->max_redirects(1);
$t->get_ok('/info/penx2')
->status_is(200)
->text_like('h1' => qr/\QFlatinfo Business-Apartment Hietzing\E/)
->content_like( qr/\QSelected language: German\E/ )
# ...
;
done_testing();
Is there a way to tell Mojolicious to respond without all this HTML-Markup so that I can see the error-mesage immediately?
There are two things at play here.
The large debug output with the full page source is because the content_like method from Test::Mojo didn't find a match, and it's telling you in which string it was looking. That's a convenience method, but if the page is large, it's a lot of text. This might tell you that the test failed because the content was wrong. But in this specific case it didn't.
The real problem is that the test failed because you had a syntax error. You can already see that from the very first test.
$t->get_ok('/info/penx2')
->status_is(200)
This test also failed. (It's a bit confusing for people who are used to Test::WWW::Mechanize because there get_ok will also check if the response was 200 OK).
# Failed test '200 OK'
# at t/2410-topinfo.t line 12.
# got: '500'
# expected: '200'
The actual error message should be there without all that HTML markup somewhere else, because while it was doing the get_ok it would have encountered the error, which should have gone to the application log. In a unit-test, that probably is STDERR.
I don't know if you've not included it, or if it's omitted. The log should be there too I believe.
Getting back to the HTML and the actual question, the reason it's output is because Test::Mojo's content_like (and most other of its methods) uses Test::More under hood. It just dispatches to like from Test::More and passes along the page content. This in turn will always display the full string it was matching against.
In recent Test::More versions, it already uses Test2 under the hood. The relevant part that outputs the full string is here.
Unfortunately there is not much you can do about it. I'd focus on finding out why it doesn't show a proper log during the unit tests (possibly because you didn't run prove with -v), and maybe find a way to make errors come out in color, which would make it easier to read. There is a color logger for the Dancer2 framework (which I maintain), but I can't find one for Mojo there wasn't one for Mojo.
Now there is Mojo::Log::Colored, which can color individual log lines based on their log level.
use Mojo::Log::Colored;
# Log to STDERR
$app->log(
Mojo::Log::Colored->new(
# optionally set the colors
colors => {
debug => "bold bright_white",
info => "bold bright_blue",
warn => "bold green",
error => "bold yellow",
fatal => "bold yellow on_red",
}
)
);
This will give you nice colorful output to the console. Here's an example script.
$ MOJO_LOG_LEVEL=debug perl -Mojo -MMojo::Log::Colored \
-e 'a(
"/" => sub {
app->log->$_("hello world") for qw/debug info warn error fatal/;
shift->render(text=>"ok");
})->log( Mojo::Log::Colored->new )->start' \
daemon
And the output if called with $ curl localhost:3000.

cucumber test gives error - Selenium::WebDriver::Error::JavascriptError

i have a tinymca's iframe inside my page and i want to fill_in that tinymca editor with the cucumber test. whenever i run my test it gives me error that jQuery not defined
in my Gemfile
source 'http://rubygems.org'
ruby '2.0.0'
gem 'capybara'
gem 'capybara-mechanize', :git => 'git://github.com/JerryWho/capybara-mechanize.git', :branch => 'relative-redirects'
gem 'rspec'
gem 'cucumber'
gem 'launchy'
gem 'pry'
gem 'selenium-webdriver'
here is my scenario
Scenario: admin puts all the valid and require data
when Job added with all the valid and require data
Then I should see the success message.
and here is the steps for that test
Given(/^I am logged in as a company admin$/) do
visit('/')
fill_in "log", :with => "admin#email.com"
fill_in "pwd", :with => "password"
click_button "submit"
end
When(/^Job added with all the valid and require data$/) do
visit('/site/admin/posts/add/')
within_frame 'questiontextarea_ifr' do
page.execute_script("jQuery(tinymce.editors[0].setContent('my content hersssssssssse'))")
end
click_button "Save"
end
Then(/^I should see the success message\.$/) do
page.should have_content('Success Your post has been successfully added.')
end
but it gives me error jQuery is not defined (Selenium::WebDriver::Error::JavascriptError)
It's most likely because "jQuery is not defined", as the message suggested.
Please try call without jQuery, but with native TinyMCE API:
page.execute_script("tinyMCE.activeEditor.setContent('my content hersssssssssse')")
Further reading: Test WYSIWYG editors using Selenium WebDriver in pure Ruby (not Capybara)

Problems implementing ruby geocoder using Sinatra

According to the ruby geocoder documentation (rubygeocoder.com), it's possible to use the geocoder gem with a Sinatra app, but I'm running into issues getting it to work and haven't been able to find any working examples or related stackoverflow issues either. I think the problem is due to the fact that it's a Sinatra app and not a full rails app.
My Gemfile:
source "https://rubygems.org"
ruby '2.1.2'
gem 'dotenv', '~> 0.10.0'
gem 'pg', '~> 0.17.1'
gem 'rack-flash3'
gem "sinatra"
gem "activerecord"
gem "sinatra-activerecord"
gem "geocoder"
gem 'omniauth'
gem 'omniauth-google-oauth2'
gem "sqlite3"
gem "shotgun"
The model (which has float latitude and longitude columns) that I want to search by:
class Item < ActiveRecord::Base
extend Geocoder::Model::ActiveRecord
attr_accessor :latitude, :longitude
belongs_to :profile
has_and_belongs_to_many :categories
has_many :reports, dependent: :destroy
}
Here's the app.rb code with the '/' route:
class FL < Sinatra::Base
get '/' do
#items = Item.near('Detroit, MI, US')
puts "ITEMS ARE:"
pp #items
erb :index
end
...
end
Here's the relevant app.rb contents:
require 'rubygems'
require 'sinatra/base'
require 'sinatra/flash'
require 'sinatra/activerecord'
require 'geocoder'
require 'omniauth'
require 'sinatra/flash'
require 'json'
require 'pp'
require 'rack-flash'
require './models/model_init'
require './helpers/helper'
require './auth'
require './admin'
require './api'
class FL < Sinatra::Base
set :root, File.dirname(__FILE__)
enable :logging
enable :sessions
#set :logging, true
register Sinatra::ActiveRecordExtension
register Sinatra::Flash
set :show_exceptions, true if ENV['RACK_ENV'] == 'development'
use Rack::Session::Cookie, :secret => ENV['RACK_COOKIE_SECRET']
end
Finally, here is the error i receive:
NoMethodError - undefined method `near' for #<Class:0x0000010750d0b8>:
/Users/bob/.rvm/gems/ruby-2.1.2/gems/activerecord-4.1.0/lib/active_record/dynamic_matchers.rb:26:in `method_missing'
/Users/bob/rails_projects/fl2/api.rb:21:in `block in <class:FL>'
/Users/bob/.rvm/gems/ruby-2.1.2/gems/sinatra-1.4.5/lib/sinatra/base.rb:1603:in `call'
/Users/bob/.rvm/gems/ruby-2.1.2/gems/sinatra-1.4.5/lib/sinatra/base.rb:1603:in `block in compile!'
/Users/bob/.rvm/gems/ruby-2.1.2/gems/sinatra-1.4.5/lib/sinatra/base.rb:966:in `[]'
/Users/bob/.rvm/gems/ruby-2.1.2/gems/sinatra-1.4.5/lib/sinatra/base.rb:966:in `block (3 levels) in route!'
Looking at the stacktrace, it looks like its not finding the geocoder package for some reason. I'm not sure if if it's a simple configuration that I'm missing, or if what I'm attempting isn't possible without some gem customization (something beyond my understanding at this point). Any insight, suggestions to try, or examples would be much appreciated. thanks!
Adding my config.ru:
config.ru
require 'bundler/setup'
Bundler.require(:default)
use Bundler.setup(:default) #added this by suggestion
require 'logger'
use Rack::Deflater
Dotenv.load
require "./fl_app"
run FL
I found a solution to this issue, but can't explain why it works. I had to add the line:
reverse_geocoded_by :latitude, :longitude
to my Item model. Once I added that line I was able to use geocoder's 'near' method.
Even though I'm not actually doing any geocoding (converting lat/long to addresses, or vice versa), it still appears to be necessary for the library to work correctly. Thanks #iain for all your helpful advice.

Sinatra: Template engine not found: prawn

I'm a newbie with Sinatra and prawn. I succeeded with erb and xmm/builder templates. Now trying to get pdf generation with prawn working.
Error received: Template engine not found: prawn
Code:
require 'rubygems'
require 'sinatra'
require 'sinatra/prawn'
set :prawn, { :page_layout => :portrait }
get '/pdf' do
content_type 'application/pdf'
prawn :pdf1
end
Thanks.
Found it: The gem from sbfaulkner doesn't work with current version of Sinatra.
Fix: install the forked gem from danielberkompas as follows:
gem install dberkom-sinatra-prawn -s http://gems.github.com
See issue 6
Then the above code works fine.

Sinatra and Haml: strange behaviour after gem update

I've made a site using Haml and Sinatra. After the update (I guess it was after that) the site didn't work any more; here is a minimal example:
/app.rb:
require 'rubygems' if RUBY_VERSION < '1.9'
require 'sinatra'
require 'haml'
get "/" do
haml :index
end
/views/layout.haml
!!!
%html{ :xmlns => "http://ww.w3.org/1999/xhtml", :lang => "en", "xml:lang" => "en" }
%head
%title test
%body
= yield
/view/index.haml
%p test
and it throws me the following exception:
/usr/lib/ruby/gems/1.9.1/gems/tilt-1.3.2/lib/tilt/template.rb in initialize
raise ArgumentError, "file or block required" if (#file || block).nil?
/usr/lib/ruby/gems/1.9.1/gems/sinatra-1.3.0.a/lib/sinatra/base.rb in new
template.new(path, 1, options)
/usr/lib/ruby/gems/1.9.1/gems/sinatra-1.3.0.a/lib/sinatra/base.rb in block in compile_template
template.new(path, 1, options)
/usr/lib/ruby/gems/1.9.1/gems/tilt-1.3.2/lib/tilt.rb in fetch
#cache[key] ||= yield
/usr/lib/ruby/gems/1.9.1/gems/sinatra-1.3.0.a/lib/sinatra/base.rb in compile_template
template_cache.fetch engine, data, options do
/usr/lib/ruby/gems/1.9.1/gems/sinatra-1.3.0.a/lib/sinatra/base.rb in render
template = compile_template(engine, data, options, views)
/usr/lib/ruby/gems/1.9.1/gems/sinatra-1.3.0.a/lib/sinatra/base.rb in haml
render :haml, template, options, locals
I haven't really found a way to fix it, does anyone know how to interpret it?
I get the same error with Sinatra 1.3.0.a (the version you're using, which I assume is a release candidate and not a full release), but updating to the current latest (1.3.0.e) fixes it, as does downgrading to the latest stable release (1.2.6). So your answer is upgrade or downgrade.
You can load a specific version of a gem using:
gem "sinatra", "=1.2.6"
before you call require "sinatra", or you could look into using Bundler (which uses the same syntax).