uninitialized constant BikeShare (NameError) - ruby

I'm trying to implement some simple testing in rspec for a gem I'm writing. When I comment out describe BikeShare do down to end and run the file, the file loads in and runs successfully. I'm sure it's something tiny I'm missing.
My test file is really simple and looks like this:
require 'spec_helper'
describe BikeShare do
it "should run" do
# response = BikeShare.new
# response.should_be present
end
end
When run, I get the error uninitialized constant BikeShare (NameError) at line 3.
My bikeshare.rb file looks like this, fairly simple:
class BikeShare
def initialize
response = JSON.parse(open("http://bayareabikeshare.com/stations/json").read)
#response = response["stationBeanList"]
end
def get_last_station
#response.last["id"]
end
end
My Rakefile looks like this:
require 'rubygems'
require 'bundler'
Bundler.setup
Bundler::GemHelper.install_tasks
require 'rspec/core/rake_task'
RSpec::Core::RakeTask.new do |spec|
# spec.libs << 'lib' << 'spec'
spec.pattern = 'spec/*_spec.rb'
end
task :default => :spec

Your tests arent aware of BikeShare.
You need to require the file that defines your BikeShare class. I dont use rspec but I think that you normally set up your testing environment in spec_helper.rb.

Related

How to write a Ruby (Minitest) unit test that fails if I don't have the correct require statements?

I have this test:
require 'minitest/autorun'
require 'minitest/color'
require_relative '../lib/util/input_file'
class TestInputFile < Minitest::Test
def setup
#input_path = Pathname.new("/path/to/inputs")
end
def test_default_input_file
input_file = Util::InputFile.new(1)
expected_path = #input_path.join('input01.txt')
assert_equal(expected_path, input_file.abspath)
end
# more tests follow
end
for this code:
module Util
class InputFile
def initialize(num)
#num = num
#input_dir = Pathname.new("/path/to/inputs")
end
def abspath
basename = 'input'
return #input_dir.join(format('%s%02d.txt', basename, #num))
end
end
end
When I run this with rake test, everything passes as expected; however, when I call it from my actual main script, it chokes with uninitialized constant Util::InputFile::Pathname (NameError). When I add require 'pathname' at the top of lib/util/input_file.rb, everything is fine.
Why does the unit test not fail in the same way, and how can I refactor it such that it will fail unless I have the correct require statement in the production code?
EDIT: Rakefile is as follows:
require 'minitest/test_task'
Minitest::TestTask.create do |t|
t.test_globs = ['test/**/test*.rb']
end
To run tests separately use rake test:isolated instead of rake test.
https://github.com/minitest/minitest#rake-tasks-
It seems like one of your other tests gets Pathname loaded.
How does your Rakefile look and doesn't it get pathname required? It can explain why your test (started with rake test) goes well.
And why don't you want to require pathname at the top of lib/util/input_file.rb?

Set Up for RSpec in a Sinatra modular app

This is my first attempt with Sinatra. I built a simple classic app, set up RSpec for it, and got it working. Then, I tried to go modular, in a MVC fashion. Even though the app works in the browser, RSpec throws a NoMethodError. I've read Sinatra docs regarding RSpec, also searched a lot here in SO, but I can't find where the bug is. Any clue?
Thank you very much in advance.
Here are my relevant files:
config.ru
require 'sinatra/base'
Dir.glob('./{app/controllers}/*.rb') { |file| require file }
map('/') { run ApplicationController }
app.rb
require 'sinatra/base'
class ZerifApp < Sinatra::Base
# Only start the server if this file has been
# executed directly
run! if __FILE__ == $0
end
app/controllers/application_controller.rb
class ApplicationController < Sinatra::Base
set :views, File.expand_path('../../views', __FILE__)
set :public_dir, File.expand_path('../../../public', __FILE__)
get '/' do
erb :index
end
end
spec/spec_helper.rb
require 'rack/test'
# Also tried this
# Rack::Builder.parse_file(File.expand_path('../../config.ru', __FILE__))
require File.expand_path '../../app.rb', __FILE__
ENV['RACK_ENV'] = 'test'
module RSpecMixin
include Rack::Test::Methods
def app() described_class end
end
RSpec.configure { |c| c.include RSpecMixin }
spec/app_spec.rb
require File.expand_path '../spec_helper.rb', __FILE__
describe "My Sinatra Application" do
it "should allow accessing the home page" do
get '/'
expect(last_response).to be_ok
end
end
The error
My Sinatra Application should allow accessing the home page
Failure/Error: get '/'
NoMethodError:
undefined method `call' for nil:NilClass
# ./spec/app_spec.rb:5:in `block (2 levels) in <top (required)>'
I'm guessing you're following this recipe, correct?
The described_class in this line:
def app() described_class end
is meant to be the class under test, in this case ZerifApp. Try it like so:
def app() ZerifApp end
EDIT
It turns out the above answer is not correct about what described_class does. I assumed it was a placeholder -- actually it is an RSpec method that returns the class of the implicit subject, that is to say, the thing being tested.
The recipe at the link is misleading because of the way it recommends writing the describe block:
describe "My Sinatra Application" do
This is valid RSpec, but it does not define the subject class. Executing described_class in an example for this block will return nil. To make it work, replace the describe block:
describe ZerifApp do
Now described_class will return the expected value (ZerifApp)
https://pragprog.com/book/7web/seven-web-frameworks-in-seven-weeks
It has some source code to get some ideas from.
This has code example too. https://github.com/laser/sinatra-best-practices

Inheritance within iron workers when using the iron_worker_ruby gem

I'm considering using IronWorker a project so that I can scale it easily (high traffic expected, with lots of background jobs).
In order to stay DRY, I'm trying to define workers using inheritance but I keep getting the following error:
/usr/local/lib/site_ruby/1.9.1/rubygems/custom_require.rb:36:in `require': cannot load such file -- base_worker.rb (LoadError)
from /usr/local/lib/site_ruby/1.9.1/rubygems/custom_require.rb:36:in `require'
from /task/child_worker.rb:3:in `<top (required)>'
from /task/runner.rb:344:in `require_relative'
from /task/runner.rb:344:in `<main>'
Here is the base worker class:
# app/workers/base_worker.rb
require 'net/http'
require 'uri'
require 'json'
class BaseWorker < IronWorker::Base
attr_accessor :params
# The run method is what IronWorker calls to run your worker
def run
data = custom_run(params)
common_post_process(data)
end
def custom_run(params)
#to be overwritten in the child class
end
def common_post_process(data)
# some common post processing => DRY
....
end
end
And here is a child class :
# app/workers/child_worker.rb
require 'net/http'
require 'uri'
require 'base_worker.rb'
class ChildWorker < BaseWorker
merge "base_worker.rb"
def custom_run(params)
#custom work
end
end
Any idea on how to fix this?
I'd recommend using our next generation gem, iron_worker_ng: https://github.com/iron-io/iron_worker_ruby_ng . The iron_worker gem is deprecated. And if you want to keep it similar style to what you have, your child_worker.rb might look like this:
require 'net/http'
require 'uri'
require_relative 'base_worker.rb'
class ChildWorker < BaseWorker
def custom_run(params)
#custom work
end
end
# NG gem doesn't run anything in particular, so to run your method:
cw = ChildWorker.new
cw.custom_run(params)
And in a child_worker.worker file:
runtime 'ruby'
file 'base_worker.rb'
exec 'child_worker.rb'
Then to upload it to IronWorker:
iron_worker upload child_worker
Then you can start queuing jobs for it:
worker = IronWorkerNG::Client.new
worker.tasks.create("child_worker", params)
If you use iron_worker_ng, it also possible to define a run method. This method will be called when the IronWorker runs. You have to specify the Class within the .worker file.
# child_worker.rb
class ChildWorker
def run
puts "doing the hard work"
end
end
And the child_worker.worker file:
# child_worker.worker
runtime 'ruby'
name 'ChildWorker'
exec 'child_worker.rb', 'ChildWorker'

RSpec test fails on Travis-CI but on local machine pass successfully

I'm write some specs to cover my HTML helpers
describe Sinatra::Helpers::HTML do
describe 'tag' do
it 'should retun selfclosed tag' do
Helpers.tag(:br, {}, true).should == '<br />'
end
it 'should have valid attributes' do
Helpers.tag(:div, :class => 'test').should include("class='test'")
end
it 'should contain value returned from block' do
tag = Helpers.tag(:div) { 'Block value' }
tag.should include('Block value')
end
end
describe 'stylesheet_tag' do
it 'should return link tag' do
Helpers.stylesheet_tag('test').should include('link')
end
it 'should contain path to asset' do
end
end
end
When I run it on local machine all is good, everything pass. But after pushing to GitHub repo Travis fails and write that Object::Sinatra is uninitialized (link) and I haven't idea why.
spec_helper.rb looks:
ENV['RACK_ENV'] = "test"
require 'simplecov'
SimpleCov.start
require File.join(File.dirname(__FILE__), '..', 'boot')
require 'rspec'
require 'capybara/rspec'
require 'rack/test'
require 'factory_girl'
FactoryGirl.find_definitions
Capybara.app = Orodruin.rack
RSpec.configure do |config|
config.include Rack::Test::Methods
config.after(:each) do
MongoMapper.database.collections.each do |collection|
collection.remove unless collection.name.match(/^system\./)
end
end
end
class Helpers
extend(*Sinatra::Base.included_modules.map(&:to_s).grep(/Helpers/).map(&:constantize))
end
because http://travis-ci.org/#!/orodruin/orodruin/jobs/2248831/L73 isn't using bundle exec.
the "bundle exec rake" line above it didn't seem to do anything.
you will need to prefix that line with bundle exec.
I don't see that line in your code, but it could be hard coded in one of your gems or in the Travis service.
The real problem is that the sinatra gem isn't found when Travis is running the specs. This is because travis is using an RVM gemset, and you are probably using the "global" gemset.
The result is ruby -s rspec ... isn't being ran in the gem bundle environment and isn't loading Sinatra.
I've forgot to add require 'spec_helper' on top of my specfile.

Webrat Mechanize outside of Rails

I'm trying to use Webrat in a standalone script to automate some web browsing. How do I get the assert_contain method to work?
require 'rubygems'
require 'webrat'
include Webrat::Methods
include Webrat::Matchers
Webrat.configure do |config|
config.mode = :mechanize
end
visit 'http://gmail.com'
assert_contain 'Welcome to Gmail'
I get this error
/usr/lib/ruby/gems/1.8/gems/webrat-0.6.0/lib/webrat/core/matchers/have_content.rb:57:in 'assert_contain': undefined method assert' for #<Object:0xb7e01958> (NoMethodError)
assert_contain and other assertions are methods of test/unit, try to require it and use webrat from inside a test method:
require 'test/unit'
class TC_MyTest < Test::Unit::TestCase
def test_fail
assert(false, 'Assertion was false.')
end
end
anyway i haven't tested it but I have a working spec_helper for rspec if this can interest you:
require File.dirname(__FILE__) + "/../config/environment" unless defined?(RAILS_ROOT)
require 'spec/rails'
require "webrat"
Webrat.configure do |config|
config.mode = :rails
end
module Spec::Rails::Example
class IntegrationExampleGroup < ActionController::IntegrationTest
def initialize(defined_description, options={}, &implementation)
defined_description.instance_eval do
def to_s
self
end
end
super(defined_description)
end
Spec::Example::ExampleGroupFactory.register(:integration, self)
end
end
plus a spec:
# remember to require the spec helper
describe "Your Context" do
it "should GET /url" do
visit "/url"
body.should =~ /some text/
end
end
give it a try I found it very useful (more than cucumber and the other vegetables around) when there is no need to Text specs (features) instead of Code specs, that I like the most.
ps you need the rspec gem and it installs the 'spec' command to execute your specs.

Resources