Sinatra, Mongoid, Heroku, MongoHQ: connecting to Mongodb - ruby

Trying to get Mongoid up and running with Sinatra on Heroku (MongoHQ). Previous experience with Rails but first time with the stack and Sinatra.
Started with one of the simple examples on the web (app.rb):
require 'rubygems'
require 'sinatra'
require 'mongo'
require 'mongoid'
configure do
Mongoid.load!('mongoid.yml')
Mongoid.configure do |config|
if ENV['MONGOHQ_URL']
conn = Mongo::Connection.from_uri(ENV['MONGOHQ_URL'])
uri = URI.parse(ENV['MONGOHQ_URL'])
# problem happens here
config.master = conn.db(uri.path.gsub(/^\//, ''))
else
config.master = Mongo::Connection.from_uri("mongodb://localhost:27017").db('test')
end
end
end
# Models
class Counter
include Mongoid::Document
field :count, :type => Integer
def self.increment
c = first || new({:count => 0})
c.inc(:count, 1)
c.save
c.count
end
end
# Controllers
get '/' do
"Hello visitor n" + Counter.increment.to_s
end
For reference, mongoid.yml looks like:
development:
sessions:
default:
database: localhost
production:
sessions:
default:
uri: <%= ENV['MONGOHQ_URL'] %>
As per app.rb (# problem happens here), my logs say:
/app/app.rb:15:in `block (2 levels) in <top (required)>': undefined method `master=' for Mongoid::Config:Module (NoMethodError)
from /app/vendor/bundle/ruby/1.9.1/gems/mongoid-3.0.3/lib/mongoid.rb:112:in `configure'
from /app/app.rb:11:in `block in <top (required)>'
from /app/vendor/bundle/ruby/1.9.1/gems/sinatra-1.3.2/lib/sinatra/base.rb:1273:in `configure'
from /app/app.rb:8:in `<top (required)>'
I have also tried variants, including:
config.master = Mongo::Connection.from_uri(ENV['MONGOHQ_URL']).db('appXXXXX')
Mongoid.database = Mongo::Connection.from_uri(ENV['MONGOHQ_URL']).db('appXXXXXXX')
But get the same error:
undefined method `master` for Mongoid::Config:Module (NoMethodError)
or:
undefined method `database=` for Mongoid::Config:Module (NoMethodError)
What am I missing?

Shouldn't be
configure do
Mongoid.load!('mongoid.yml')
end
enough?
That's what the mongid docs are saying. The MONGOHQ_URL environment variable already contains every information to initialize the connection to the db.

So was using Mongoid 3.x ... which:
Doesn't use 10gen driver: uses Moped
Doesn't use config.master
The canonical sample code above which is all over the web works out of the box with Mongoid 2.x so have dropped back to that for the time being.
Thanks!

Related

Hanami: undefined method `size' for nil:NilClass

I keep learning hanami and ran into the following problem: when I initialize and check the parameters, I encounter the following error
Boot Error
Something went wrong while loading /Users/anewaccount/Projects/Mediateka/config.ru
NoMethodError: undefined method `size' for nil:NilClass
/Users/anewaccount/.rvm/gems/ruby-2.7.2/gems/dry-validation-0.11.0/lib/dry/validation/schema/deprecated.rb:11:in `input_processor'
/Users/anewaccount/.rvm/gems/ruby-2.7.2/gems/dry-validation-0.11.0/lib/dry/validation/schema/class_interface.rb:165:in `default_options'
/Users/anewaccount/.rvm/gems/ruby-2.7.2/gems/dry-validation-0.11.0/lib/dry/validation/schema/class_interface.rb:35:in `new'
/Users/anewaccount/.rvm/gems/ruby-2.7.2/gems/hanami-validations-1.3.7/lib/hanami/validations.rb:109:in `validations'
/Users/anewaccount/.rvm/gems/ruby-2.7.2/gems/hanami-controller-1.3.3/lib/hanami/action/params.rb:152:in `params'
/Users/anewaccount/.rvm/gems/ruby-2.7.2/gems/hanami-controller-1.3.3/lib/hanami/action/validatable.rb:100:in `block in params'
/Users/anewaccount/.rvm/gems/ruby-2.7.2/gems/hanami-controller-1.3.3/lib/hanami/action/validatable.rb:100:in `class_eval'
/Users/anewaccount/.rvm/gems/ruby-2.7.2/gems/hanami-controller-1.3.3/lib/hanami/action/validatable.rb:100:in `params'
/Users/anewaccount/Projects/Mediateka/apps/web/controllers/auth/sign_up.rb:11:in `<class:SignUp>'
/Users/anewaccount/Projects/Mediateka/apps/web/controllers/auth/sign_up.rb:9:in `<module:Auth>'
/Users/anewaccount/Projects/Mediateka/apps/web/controllers/auth/sign_up.rb:8:in `<module:Controllers>'
/Users/anewaccount/Projects/Mediateka/apps/web/controllers/auth/sign_up.rb:7:in `<module:Web>'
/Users/anewaccount/Projects/Mediateka/apps/web/controllers/auth/sign_up.rb:6:in `<top (required)>'
/Users/anewaccount/.rvm/gems/ruby-2.7.2/gems/hanami-utils-1.3.8/lib/hanami/utils.rb:56:in `require_relative'
/Users/anewaccount/.rvm/gems/ruby-2.7.2/gems/hanami-utils-1.3.8/lib/hanami/utils.rb:56:in `block in require!'
/Users/anewaccount/.rvm/gems/ruby-2.7.2/gems/hanami-utils-1.3.8/lib/hanami/utils.rb:94:in `each'
/Users/anewaccount/.rvm/gems/ruby-2.7.2/gems/hanami-utils-1.3.8/lib/hanami/utils.rb:94:in `for_each_file_in'
/Users/anewaccount/.rvm/gems/ruby-2.7.2/gems/hanami-utils-1.3.8/lib/hanami/utils.rb:56:in `require!'
my action:
# frozen_string_literal: true
require 'pry-byebug'
require_relative 'auth_base_action'
module Web
module Controllers
module Auth
class SignUp < AuthBaseAction
params do
required(:user).schema do
required(:first_name).filled(:str?)
required(:last_name).filled(:str?)
required(:email).filled(:str?, format?: /#/)
required(:password).filled(:str?).confirmation
end
end
def call params
binding.pry
end
end
end
end
end
I wrote the params block according to the example from the official documentation on the idea that it should work, but I catch NoMethodError: undefined method `size 'for nil: NilClass I also saw in the official documentation that these validations are delegated from Hanami :: Validations, I installed gem' hanami- validation 'according to their official documentation, but I had the same error, then I started looking at other people's code and they were successful using the example from the official documentation. Please tell me what is the error or please explain what am I doing wrong? I'm already very confused

How can I force Rspec to not falsely think another module is nested inside the parent?

I have an issue that's appearing only when running rspec, my application loads and works fine locally and in production
rspec seems to think that the gem JWT belongs to my module BACKBONE
An error occurred while loading spec_helper.
Failure/Error: JWT.encode(payload, ENV['APP_SECRET'], 'HS256')
NameError:
uninitialized constant BACKBONE::JWT
# ./lib/jwt.rb:6:in `encode'
# ./lib/backbone/policies.rb:7:in `<class:Policy>'
# ./lib/backbone/policies.rb:5:in `<module:BACKBONE>'
# ./lib/backbone/policies.rb:3:in `<top (required)>'
# ./init.rb:10:in `load'
# ./init.rb:10:in `block in <module:CrewManagement>'
# ./init.rb:10:in `glob'
# ./init.rb:10:in `<module:CrewManagement>'
# ./init.rb:4:in `<top (required)>'
# ./spec/spec_helper.rb:16:in `require'
# ./spec/spec_helper.rb:16:in `<top (required)>'
files are listed in the order they are loaded into memory, it may be useful to note that I have several other applications with the same setup that are not experiencing this issue
/spec/spec_helper.rb
require 'bundler'
require 'simplecov'
SimpleCov.start
Bundler.require :default
Dotenv.load("./.env.#{(ENV['RACK_ENV'] || 'development')}")
require 'rack/test'
require './init'
# ...
/init.rb
module CrewManagement
## ...
Dir.glob('./lib/**/*.rb') { |file| load file }
## ...
end
/lib/jwt.rb
module BACKBONE
def self.encode(payload)
JWT.encode(payload, ENV['APP_SECRET'], 'HS256')
end
def self.decode(token)
JWT.decode(token, ENV['APP_SECRET'], true, algorithm: 'HS256')
end
end
/lib/backbone/policies.rb
module BACKBONE
headers = { 'Authorization' => BACKBONE.encode(app: '...') }
end

Rspec, capybara getting started issues

I have have started with simple example of Rspec,Capybara. I have come across few issues. This issues are probably because I have experience with cucumber and page_object gem, but here I am using capybara and Site_prism gem.
I have tried:
my_example_spec.rb
require_relative 'Support/spec_helper'
require_relative 'pages/login_page'
describe 'My behaviour' do
it 'should do something'do
#login_page = LoginPage.new
#login_page.load
#login_page.login('autouser','password')
end
end
and login_page.rb
class LoginPage < SitePrism::Page
set_url "/login"
element :username, "input[id='username']"
element :password, "input[id='password']"
element :submit, "input[id='submit']"
def login(username,password)
#login_page.username.set username
#login_page.password.set password
#login_page.submit.click
end
end
Issues are:
When I run my_example_spec.rb it gives error
Testing started at ...
Run options: include {:full_description=>/My\ behaviour\ should\ do\ something/}
NoMethodError: undefined method `username' for nil:NilClass
./pages/login_page.rb:10:in `login'
./my_example_spec.rb:11:in `block (2 levels) in <top (required)>'
-e:1:in `load'
-e:1:in `<main>'
Shouldn't it be on(LoginPage).login (autouser, password). It should navigate to the page and run login method. It is how it works in page_object gem whats the equivalent of site_prism gem
The login method in your LoginPage class should be
def login(username,password)
username.set username
password.set password
submit.click
end
#login_page is not an instance variable of the LoginPage class so it is not accessible inside the class. It's also not necessary inside the class since you're already inside the class.

rake spec failed, it cannot load or find constant or global variable

I create standalone rspec test script to testing existing api framework. It works pretty well, but I found problem where in the Rakefile I need to assign some value from YAML file (uri link, email) either CONSTANT or $global_var the code in the Rakefile looks like this:
require 'rubygems'
require 'bundler/setup'
require 'yaml'
require 'rspec/core/rake_task'
task :default => :spec
desc 'Running rspec test'
task :spec, :option do |t, opt|
choice = opt[:choice]
if choice == "production"
puts 'Test running on production'
VAR = YAML::load(File.read(File.expand_path("../config/prod_variable.yml", __FILE__)))
elsif choice == "development"
puts 'Test running on development'
VAR = YAML::load(File.read(File.expand_path("../config/dev_variable.yml", __FILE__)))
end
puts VAR['URI'] #=> print out the value correctly
RSpec::Core::RakeTask.new do |task|
test = Rake.application.original_dir
task.fail_on_error = false
task.rspec_opts = '--format documentation --color'
end
end
When I run the rake command on the terminal, the rspec failed find the VAR constant value. Here is the error message from rspec
Failures:
1) ApiTest Testing API platform for GET request
Failure/Error: #var = ApiTest.new(VAR['URI'] ,
NameError:
uninitialized constant VAR
# ./rspec_test/api_test/api_test_get_spec.rb:8:in `block (2 levels) in <top (required)>'
2) ApiTest Testing API platform for POST request
Failure/Error: #zat = ApiTest.new(VAR['URI'] ,
NameError:
uninitialized constant VAR
# ./rspec_test/api_test/api_test_post_spec.rb:7:in `block (2 levels) in <top (required)>'
Is there any idea how to get this works? I need to get value from VAR constant or global variable, but seems ruby failed to assign the value.
If opt[:choice] is neither "production" nor "development", VAR is undefined in your code.

undefined method `infer_base_class_for_anonymous_controllers=' for #<RSpec::Core::Configuration:0x007f7fb3a62b80> (NoMethodError)

I'm currently on Chapter 7 of Hartl's Tutorial, and every time I run
bundle exec rspec spec/
the following results:
/Users/siciliana/sample_app/spec/spec_helper.rb:31:in `block in <top (required)>': undefined method `infer_base_class_for_anonymous_controllers=' for #<RSpec::Core::Configuration:0x007f7fb3a62b80> (NoMethodError)
from /usr/local/rvm/gems/ruby-2.0.0-p0/gems/rspec-core-2.6.4/lib/rspec/core.rb:79:in `configure'
from /Users/siciliana/sample_app/spec/spec_helper.rb:11:in `<top (required)>'
from /Users/siciliana/sample_app/spec/models/user_spec.rb:12:in `require'
from /Users/siciliana/sample_app/spec/models/user_spec.rb:12:in `<top (required)>'
from /usr/local/rvm/gems/ruby-2.0.0-p0/gems/rspec-core-2.6.4/lib/rspec/core/configuration.rb:419:in `load'
from /usr/local/rvm/gems/ruby-2.0.0-p0/gems/rspec-core-2.6.4/lib/rspec/core/configuration.rb:419:in `block in load_spec_files'
from /usr/local/rvm/gems/ruby-2.0.0-p0/gems/rspec-core-2.6.4/lib/rspec/core/configuration.rb:419:in `map'
from /usr/local/rvm/gems/ruby-2.0.0-p0/gems/rspec-core-2.6.4/lib/rspec/core/configuration.rb:419:in `load_spec_files'
from /usr/local/rvm/gems/ruby-2.0.0-p0/gems/rspec-core-2.6.4/lib/rspec/core/command_line.rb:18:in `run'
from /usr/local/rvm/gems/ruby-2.0.0-p0/gems/rspec-core-2.6.4/lib/rspec/core/runner.rb:80:in `run_in_process'
from /usr/local/rvm/gems/ruby-2.0.0-p0/gems/rspec-core-2.6.4/lib/rspec/core/runner.rb:69:in `run'
from /usr/local/rvm/gems/ruby-2.0.0-p0/gems/rspec-core-2.6.4/lib/rspec/core/runner.rb:11:in `block in autorun'
Can someone please explain what is happening here to an absolute newbie?
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'
require 'rspec/autorun'
#
RSpec.configure do |config|
# ## Mock Framework
#
# If you prefer to use mocha, flexmock or RR, uncomment the appropriate line:
#
# config.mock_with :mocha
# config.mock_with :flexmock
# config.mock_with :rr
# Remove this line if you're not using ActiveRecord or ActiveRecord fixtures
config.fixture_path = "#{::Rails.root}/spec/fixtures"
# If you're not using ActiveRecord, or you'd prefer not to run each of your
# examples within a transaction, remove the following line or assign false
# instead of true.
config.use_transactional_fixtures = true
# If true, the base class of anonymous controllers will be inferred
# automatically. This will be the default behavior in future versions of
# rspec-rails.
config.infer_base_class_for_anonymous_controllers = false
# Run specs in random order to surface order dependencies. If you find an
# order dependency and want to debug it, you can fix the order by providing
# the seed, which is printed after each run.
# --seed 1234
config.order = "random"
end
I was getting the same error (although not following the tutorial).
I believe this setting requires 'rspec/rails'
My solution was to move the line
config.infer_base_class_for_anonymous_controllers = # whatever
From spec_helper.rb to rails_helper.rb.

Resources