Codeship, Sinatra, ActiveRecord - configuration - ruby

I have a sinatra app working on my computer and am trying to get the tests to run on Codeship. I've reduced it to a tiny subset to see if I can sort out the problem I am having. I would greatly appreciate another pair of eyes...
Here are the key files:
Rakefile:
require 'sinatra/activerecord/rake'
require 'rake/testtask'
require_relative "demo_app"
Rake::TestTask.new do |t|
t.pattern = "test/*_test.rb"
end
database.yml
development:
adapter: sqlite3
database: db/development.sqlite3
test:
adapter: sqlite3
database: db/test.sqlite3
production:
url: <%= ENV['DATABASE_URL'] %>
demo_app.rb:
require 'sinatra/activerecord'
require './models/event'
require './models/person'
require './models/registration'
require 'pry-byebug'
migrations:
class CreateEvents < ActiveRecord::Migration
def change
create_table :events do |t|
t.string :name
t.date :date
end
end
end
test_helper.rb:
ENV['RACK_ENV'] = "test"
ENV["SINATRA_ENV"] = "test"
require_relative '../demo_app'
require 'minitest/autorun'
require 'rack/test'
ActiveRecord::Migration.maintain_test_schema!
event_test.rb:
require_relative './test_helper.rb'
describe Event do
it "can add events" do
Event.create(name: "An Event")
Event.create(name: "Another Event")
Event.all.size.must_equal 2
end
end
So, with that context I setup Codeship. Here are the key settings there:
Setup commands:
rvm use 2.2.2
bundle install
RACK_ENV=test bundle exec rake db:migrate
Test Pipeline (1 of 1)
rake test
And now when I push to git, and codeship picks it up I get this error on line 1 of demo_app.rb which is a require to sinatra/activerecord:
rake aborted!
Database URL cannot be empty
.....
It seems that for some reason, it is not paying attention to the fact that I am running in test mode and so it should use the test clause of database.yml.
Thoughts?

Related

Rake not running any tests with minitest

I have a file containing a class of multiple tests (using minitest). I have require 'minitest/autorun' at the top of the file and all tests run correctly when I call the file directly (ruby my_tests.rb).
So far, so good. However, now I'm trying to run my tests via rake.
require "rake/testtask"
task :default => [:test]
Rake::TestTask.new do |t|
t.libs << Dir.pwd + "/lib/examples"
t.test_files = FileList['test/test*.rb']
end
Calling rake shows test/my_test.rb getting called but no tests within the class get run (0 tests, 0 assertions, etc.). I do get these warnings:
...gems/minitest-5.8.0/lib/minitest/assertions.rb:17: warning: already initialized constant MiniTest::Assertions::UNDEFINED
...ruby/2.1.0/lib/ruby/2.1.0/minitest/unit.rb:80: warning: previous definition of UNDEFINED was here
How can I run my tests within rake successfully? I am not using rails.
EDIT: Here is the top of my test file:
require 'minitest/spec'
require 'minitest/autorun'
require 'minitest/reporters'
reporter_options = { color: true }
Minitest::Reporters.use![Minitest::Reporters::DefaultReporter.new(reporter_options)]
class Test_PowerSpecInputs < Minitest::Test
def setup
#mc = TestClass.new()
end
def test_does_lib_have_constant
# my test code
end
end
Try changing your Rakefile to this.
require "bundler/gem_tasks"
require "rake/testtask"
Rake::TestTask.new(:test) do |t|
t.libs << "test"
t.libs << "lib"
t.test_files = FileList['test/**/*_test.rb']
end
task :default => :test
jphager2 got me thinking about tool versions and it turned out that my version of rake was fairly old. Updating to 11.x did the trick.

ActiveSupport TestCase not running in Sinatra

I'm setting up a new Sinatra app and am having issues getting my tests to run via a rake task. When I run rake:test, the task runs, shows me which files it will be running, but nothing happens. I know it's loading the class because it has failed due to syntax errors, but I never see my tests running. What am I missing? Below is my configuration and example test:
rakefile.rb
require "rake/testtask"
require "sinatra/activerecord/rake"
require "./app"
task :default => :test
TEST_FILES = FileList["test/**/test*.rb"]
desc "Run all of the tests for redFish"
Rake::TestTask.new do |t|
t.libs << "test"
t.test_files = TEST_FILES
t.verbose = true
end
task :default => "test"
test/test_helper.rb
ENV["RACK_ENV"] = "test"
require "rack/test"
require "awesome_print"
require "active_support"
require "active_support/core_ext"
/test/unit/test_organization.rb
require File.expand_path '../../test_helper.rb',__FILE__
class TestOrganization < ActiveSupport::TestCase
def setup
puts "setup for tests"
end
test "validates_required_fields" do
puts "RUNNING TESTS"
assert true
refute false
end
end
When I run rake:test, I can see that test_helper and test_organization.rb are being found by the TestTask, but I don't see any tests pass/fail.
Am I missing something obvious?
Looks like the issue was caused by not requiring minitest/autorun in my test helper. I added that line, and the tests ran fine.

Unable to make a rake-tasks file and make it work properly

I decided to create a rake tasks for my Sinatra project and not to use the ready ones.
#Rakefile
require 'rake/testtask'
require 'rake/clean'
Dir.glob("tasks/*.rake").each { |r| import r }
#/tasks/seed.rake
require 'rubygems'
require 'bundler'
Bundler.require
require 'mongoid'
require_relative '../models/user'
namespace :db do
task :seed do
puts 'Creating a user....'
user1 = User.new email: "email1#gmail.com", password: "test123"
user1.save!
puts 'User has been created.'
end
end
#user.rb
require 'bcrypt'
require 'digest/md5'
require 'openssl'
class User
include Mongoid::Document
include Mongoid::Timestamps
#.........
#gemfile (partly)
source 'http://rubygems.org'
gem 'bcrypt-ruby', require: 'bcrypt'
And I've got the error of "Creating a user....
rake aborted!
undefined method `create!' for BCrypt::Password:Class
/home/alex/ruby_projects/service/models/user.rb:47:in `password='"
where #47 looks like
def password= pass
self.hashed_password = BCrypt::Password.create! pass, cost: 10
end
Note that in normal development everything works just fine. So I missed to require a file I think.
Your thoughts?
p.s. Even if I put
require 'bcrypt'
require 'digest/md5'
require 'openssl
to /tasks/seed.rake the error remains.
It appears you are using a non-existant method from BCrypt::Password. According to the docs, there is only a .create method and no .create! method. Switch to BCrypt::Password.create and it should work.
def password= pass
self.hashed_password = BCrypt::Password.create pass, cost: 10
end

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.

Generate migrations outside Rails

I'm using ActiveRecord outside Rails. I would want a program to generate the skeleton of a migration ( as well as a system to collect and maintain them ).
Can anyone make a suggestion?
Also take a look at new active_record_migrations
There is a gem to use Rails Database Migrations in non Rails projects. Its name is "standalone_migrations"
Here is a link
https://github.com/thuss/standalone-migrations
If you do not like to use rake, but still get the system part of ActiveRecord::Migration, then you can use the following to handle the ups and downs from plain ruby (without any rails):
require 'active_record'
require 'benchmark'
# Migration method, which does not uses files in db/migrate but in-memory migrations
# Based on ActiveRecord::Migrator::migrate
def migrate(migrations, target_version = nil)
direction = case
when target_version.nil?
:up
when (ActiveRecord::Migrator::current_version == target_version)
return # do nothing
when ActiveRecord::Migrator::current_version > target_version
:down
else
:up
end
ActiveRecord::Migrator.new(direction, migrations, target_version).migrate
puts "Current version: #{ActiveRecord::Migrator::current_version}"
end
# MigrationProxy deals with loading Migrations from files, we reuse it
# to create instances of the migration classes we provide
class MigrationClassProxy < ActiveRecord::MigrationProxy
def initialize(migrationClass, version)
super(migrationClass.name, version, nil, nil)
#migrationClass = migrationClass
end
def mtime
0
end
def load_migration
#migrationClass.new(name, version)
end
end
# Hash of all our migrations
migrations = {
2016_08_09_2013_00 =>
class CreateSolutionTable < ActiveRecord::Migration[5.0]
def change
create_table :solution_submissions do |t|
t.string :problem_hash, index: true
t.string :solution_hash, index: true
t.float :resemblance
t.timestamps
end
end
self # Necessary to get the class instance into the hash!
end,
2016_08_09_2014_16 =>
class CreateProductFields < ActiveRecord::Migration[5.0]
# ...
self
end
}.map { |key,value| MigrationClassProxy.new(value, key) }
ActiveRecord::Base.establish_connection(
:adapter => 'sqlite3',
:database => 'XXX.db'
)
# Play all migrations (rake db:migrate)
migrate(migrations, migrations.last.version)
# ... or undo them (rake db:migrate VERSION=0)
migrate(migrations, 0)
class ApplicationRecord < ActiveRecord::Base
self.abstract_class = true
end
class SolutionSubmission < ApplicationRecord
end
I have made a minimal example of how to use active record outside of Rails. Rails migrations (Standalone migrations) in non-Rails (and non Ruby) projects.
https://github.com/euclid1990/rails-migration
(Support Rails >= 5.2)
You can refer Rake file in this repo.
There is another gem called otr-activerecord. This gem provides following tasks:
rake db:create
rake db:create_migration[name]
rake db:drop
rake db:environment:set
rake db:fixtures:load
rake db:migrate
rake db:migrate:status
rake db:rollback
rake db:schema:cache:clear
rake db:schema:cache:dump
rake db:schema:dump
rake db:schema:load
rake db:seed
rake db:setup
rake db:structure:dump
rake db:structure:load
rake db:version
All you need to do is to install it and add a Rakefile with content
load 'tasks/otr-activerecord.rake'
OTR::ActiveRecord.configure_from_file! 'config/database.yml'
I prefer this gem over active_record_migrations or Standalone Migration because those two gems depend on railties, which is almost the entire Rails. For example, Nokogiri takes a long time to compile, and takes a lot of spaces.

Resources