Mongoid and Rspec error Mongo::Error::NoServerAvailable: - ruby

When I am starting my Rspec test, I get this error:
1) User checks if the user is created
Failure/Error: expect{ #user_test = create(:user) }.to change { User.count }
Mongo::Error::NoServerAvailable:
No server is available matching preference: #<Mongo::ServerSelector::Primary:0x70316515164800 tag_sets=[] max_staleness=nil> using server_selection_timeout=30 and local_threshold=0.015
# /Users/aliceguillaume/.rvm/gems/ruby-2.3.4/gems/mongo-2.5.0/lib/mongo/server_selector/selectable.rb:115:in `select_server'
# /Users/aliceguillaume/.rvm/gems/ruby-2.3.4/gems/mongo-2.5.0/lib/mongo/collection/view/readable.rb:139:in `block in count'
# /Users/aliceguillaume/.rvm/gems/ruby-2.3.4/gems/mongo-2.5.0/lib/mongo/retryable.rb:44:in `read_with_retry'
# /Users/aliceguillaume/.rvm/gems/ruby-2.3.4/gems/mongo-2.5.0/lib/mongo/collection/view/readable.rb:138:in `count'
# /Users/aliceguillaume/.rvm/gems/ruby-2.3.4/gems/mongoid-5.2.1/lib/mongoid/contextual/mongo.rb:70:in `block in count'
# /Users/aliceguillaume/.rvm/gems/ruby-2.3.4/gems/mongoid-5.2.1/lib/mongoid/contextual/mongo.rb:504:in `try_cache'
# /Users/aliceguillaume/.rvm/gems/ruby-2.3.4/gems/mongoid-5.2.1/lib/mongoid/contextual/mongo.rb:70:in `count'
# /Users/aliceguillaume/.rvm/gems/ruby-2.3.4/gems/mongoid-5.2.1/lib/mongoid/contextual.rb:20:in `count'
# /Users/aliceguillaume/.rvm/gems/ruby-2.3.4/gems/mongoid-5.2.1/lib/mongoid/findable.rb:55:in `count'
# ./spec/models/user_spec.rb:11:in `block (3 levels) in <top (required)>'
# ./spec/models/user_spec.rb:11:in `block (2 levels) in <top (required)>'
Finished in 30.14 seconds (files took 8.39 seconds to load)
1 example, 1 failure
Failed examples:
rspec ./spec/models/user_spec.rb:10 # User checks if the user is created
I am really confused about it.
My mongo server is running too.
My user_spec.rb:
require 'spec_helper'
require 'rails_helper'
require 'database_cleaner'
DatabaseCleaner.strategy = :truncation
RSpec.describe User, :type => :model do
it "checks if the user is created" do
expect{ #user_test = create(:user) }.to change { User.count }
end
end
Any idea why my mongo won't work?

Found the answer
My config file had mistake so I change it to :
test:
clients:
default:
database: test
hosts:
- 127.0.0.1:27017
options:
read:
mode: :primary
max_pool_size: 1
log_level: :debug

Related

Added Timeout to method, and now the first spec always fails

I recently added a timeout to a method that is used by about a dozen different commands in the class. Here is the method:
def exec_mc!(command)
begin
Timeout.timeout(30.minutes) do
library_motion_logger ||= ::Logging.logger["#library_logger.name}::Motion"]
library_motion_logger.info("Executing mc command 'mc #{command}' ...")
result = rcm_ssh.execute("/RCM_code/mc #{command}")
# TODO: Can this be the result.success method instead, which checks for empty stderr also
# Match the time pattern from mc
success = result.exit_code.zero?
MotionCommandResult.new(success, result.execution_time, result.stdout, result.stderr)
end
rescue Timeout::Error
# Something is wrong. Fail out now.
library_motion_logger.warn("Timed out while waiting for mc command '#{command}'")
false
end
end
Now when I run rspec, the first spec fails no matter which one is ran first. If I run a single spec, that also fails. Here is what I am seeing as the failure:
1) Library::Motion::MotionCommander#gather behaves like basic motion command with successful result should receive execute("/RCM_code/mc --gather", *(any args)) 1 time
Failure/Error: #library_gem_logger ||= ::Logging.logger[LIBRARY_GEM_LOGGER_ROOT_DEFAULT]
Timeout::Error:
execution expired
As you can see, it says that the error occurs while trying to get the logger in the very first line of my begin block. If I remove this line, I get the same error on the next line. So basically I am always getting an error on the first line of the first spec, no matter what. I have tried moving things around and this has held true. What can I do to fix this?
Edit: Here are some of the specs
def stub_and_expect_mc(exits = [], stderrs = [], stdouts = [])
full_command = "/RCM_code/mc #{command}"
ssh_stub_and_expect(full_command, exits, stderrs, stdouts)
end
shared_examples 'basic motion command' do
context 'with successful result' do
before :each do
stub_and_expect_mc(0)
end
it { is_expected.to have_attributes(success: true) }
end
context 'with unsuccessful result' do
before :each do
stub_and_expect_mc(1)
end
it { is_expected.to have_attributes(success: false) }
end
end
describe '#random_slot_to_slot' do
let(:command) { '--randomslot' }
subject { #library.random_slot_to_slot }
it_behaves_like 'basic motion command'
end
describe '#drawer_to_drawer' do
# Extra space before --srcdrawer since no mover number is specified
let(:command) { "--drawertodrawer --srcdrawer #{src_drawer} --destdrawer #{dest_drawer} --force" }
let(:src_drawer) { SpectraLibrary::Motion::HydraDrawer.new(0, 0, 1, 0, '', '', 1) }
let(:dest_drawer) { SpectraLibrary::Motion::HydraDrawer.new(0, 0, 2, 0, '', '', 2) }
subject { #library.drawer_to_drawer(src_drawer, dest_drawer) }
it_behaves_like 'basic motion command'
end
Edit 2: Here are the last three times I ran specs, with the rescue removed so you can see the actual failure (otherwise it just shows the result was false)
Failures:
1) SpectraLibrary::Motion::MotionCommander#gather behaves like basic motion command with successful result should receive execute("/RCM_code/mc --gather", *(any args)) 1 time
Failure/Error: #library_gem_logger ||= ::Logging.logger[LIBRARY_GEM_LOGGER_ROOT_DEFAULT]
Timeout::Error:
execution expired
Shared Example Group: "basic motion command" called from ./spec/lib/spectra_library/motion/motion_commander_spec.rb:80
# ./lib/spectra_library/logging.rb:15:in `library_gem_logger'
# ./lib/spectra_library/logging.rb:28:in `library_logger'
# ./lib/spectra_library/logging.rb:35:in `library_motion_logger'
# ./lib/spectra_library/motion/motion_commander.rb:150:in `block in exec_mc!'
# ./lib/spectra_library/motion/motion_commander.rb:148:in `exec_mc!'
# ./lib/spectra_library/motion/motion_commander.rb:95:in `gather'
# ./spec/lib/spectra_library/motion/motion_commander_spec.rb:79:in `block (3 levels) in <top (required)>'
# ./spec/lib/spectra_library/motion/motion_commander_spec.rb:20:in `block (4 levels) in <top (required)>'
Finished in 0.09762 seconds (files took 0.72568 seconds to load)
30 examples, 1 failure
Failures:
1) SpectraLibrary::Motion::MotionCommander#drawer_to_drawer behaves like basic motion command with successful result should receive execute("/RCM_code/mc --drawertodrawer --srcdrawer #<SpectraLibrary::Motion::HydraDrawer:0x000055710f024e20> --destdrawer #<SpectraLibrary::Motion::HydraDrawer:0x000055710f024d30> --force", *(any args)) 1 time
Failure/Error: #library_gem_logger ||= ::Logging.logger[LIBRARY_GEM_LOGGER_ROOT_DEFAULT]
Timeout::Error:
execution expired
Shared Example Group: "basic motion command" called from ./spec/lib/spectra_library/motion/motion_commander_spec.rb:42
# ./lib/spectra_library/logging.rb:15:in `library_gem_logger'
# ./lib/spectra_library/logging.rb:28:in `library_logger'
# ./lib/spectra_library/logging.rb:35:in `library_motion_logger'
# ./lib/spectra_library/motion/motion_commander.rb:150:in `block in exec_mc!'
# ./lib/spectra_library/motion/motion_commander.rb:149:in `exec_mc!'
# ./lib/spectra_library/motion/motion_commander.rb:29:in `drawer_to_drawer'
# ./spec/lib/spectra_library/motion/motion_commander_spec.rb:41:in `block (3 levels) in <top (required)>'
# ./spec/lib/spectra_library/motion/motion_commander_spec.rb:20:in `block (4 levels) in <top (required)>'
Finished in 0.08525 seconds (files took 0.75393 seconds to load)
30 examples, 1 failure
Failures:
1) SpectraLibrary::Motion::MotionCommander#drawer_to_drawer behaves like basic motion command with successful result should receive execute("/RCM_code/mc --drawertodrawer --srcdrawer #<SpectraLibrary::Motion::HydraDrawer:0x000055ef29d2efd8> --destdrawer #<SpectraLibrary::Motion::HydraDrawer:0x000055ef29d2ef38> --force", *(any args)) 1 time
Failure/Error: #library_gem_logger ||= ::Logging.logger[LIBRARY_GEM_LOGGER_ROOT_DEFAULT]
Timeout::Error:
execution expired
Shared Example Group: "basic motion command" called from ./spec/lib/spectra_library/motion/motion_commander_spec.rb:42
# ./lib/spectra_library/logging.rb:15:in `library_gem_logger'
# ./lib/spectra_library/logging.rb:28:in `library_logger'
# ./lib/spectra_library/logging.rb:35:in `library_motion_logger'
# ./lib/spectra_library/motion/motion_commander.rb:150:in `block in exec_mc!'
# ./lib/spectra_library/motion/motion_commander.rb:149:in `exec_mc!'
# ./lib/spectra_library/motion/motion_commander.rb:29:in `drawer_to_drawer'
# ./spec/lib/spectra_library/motion/motion_commander_spec.rb:41:in `block (3 levels) in <top (required)>'
# ./spec/lib/spectra_library/motion/motion_commander_spec.rb:20:in `block (4 levels) in <top (required)>'
Finished in 0.10332 seconds (files took 0.73916 seconds to load)
30 examples, 1 failure

Rspec: No such file or directory # rb_sysopen -

I'm trying to write a simple test for a ruby script that uses gets and I'm experiencing some weird behavior.
When I run the test with rspec it passes fine, but as soon as I run rspec with any flags, like rspec -f json or rspec -O rand the test will fail and give me No such file or directory # rb_sysopen - -O, where -O is whatever the flag that was run.
Stranger still is that if I run rspec and specify the test file like rspec spec/gets_spec.rb, I get a completely different error:
Failure/Error: expect { require_relative '../gets' }.to output("Hello, Lena!\n").to_stdout
expected block to output "Hello, Lena!\n" to stdout, but output "Hello, Describe \"gets.rb\" do!\n"
Diff:
## -1,2 +1,2 ##
-Hello, Lena!
+Hello, Describe "gets.rb" do!
# ./spec/gets_spec.rb:14:in `block (2 levels) in <top (required)>'
I'm having trouble figuring out the right way to write my test so that this doesn't happen but I'm not sure what part of my code needs to change.
I'm using ruby 2.6.3
I learned about testing input from this question
The script, gets.rb, looks like
puts "Hello, #{gets.chomp.capitalize}!"
My test looks like
describe "gets.rb" do
before do
$stdin = StringIO.new("lena")
end
after do
$stdin = STDIN
end
it "should output 'Hello, name!'" , points: 1 do
allow($stdin).to receive(:gets).and_return("lena")
expect { require_relative "../gets" }.to output("Hello, Lena!\n").to_stdout
end
end
Here's the full failure message:
Failures:
1) gets.rb should output 'Hello, name!'
Failure/Error: expect { require_relative '../gets' }.to output("Hello, Lena!\n").to_stdout
Errno::ENOENT:
No such file or directory # rb_sysopen - -O
#./gets.rb:1:in `gets'
# ./gets.rb:1:in `gets'
# ./gets.rb:1:in `<top (required)>'
# ./spec/gets_spec.rb:14:in `require_relative'
# ./spec/gets_spec.rb:14:in `block (3 levels) in <top (required)>'
# ./spec/gets_spec.rb:14:in `block (2 levels) in <top (required)>'
You can try to use a little different approach:
describe "gets.rb" do
it "should output 'Hello, name!'" do
allow_any_instance_of(Object).to receive(:gets).and_return("lena")
expect { require_relative "../gets.rb" }.to output("Hello, Lena!\n").to_stdout
end
end
allow_any_instance_of I took from https://makandracards.com/makandra/41096-stubbing-terminal-user-input-in-rspec
Reading user input in console applications is usually done using Kernel#gets.
The page suggests to use Object.any_instance.stub(gets: 'user input') but it's deprecated syntax already and I've updated it.

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 "Failure/Error: Unable to find matching line from backtrace" On every test

I am working through some Ruby problem sets. I'm using Ubuntu 14.04, rbenv 0.4.0-98-g13a474c, rspec 3.1.4, and ruby 2.0.0p353. I'm running into the following errors for every test I run and I'm hoping someone might be able to guide me in the right direction to a solution.
I have run rspec tests successfully in the past but I can't seem to figure out the issue with my current setup.
Here is the message I receive for every test I run:
6) age is an integer
Failure/Error: Unable to find matching line from backtrace
ArgumentError:
wrong number of arguments (0 for 1)
# /usr/lib/ruby/vendor_ruby/rspec/mocks.rb:10:in `setup'
# /var/lib/gems/1.9.1/gems/rspec-core-3.1.4/lib/rspec/core/mocking_adapters/rspec.rb:19:in `setup_mocks_for_rspec'
# /var/lib/gems/1.9.1/gems/rspec-core-3.1.4/lib/rspec/core/example.rb:366:in `run_before_example'
# /var/lib/gems/1.9.1/gems/rspec-core-3.1.4/lib/rspec/core/example.rb:150:in `block in run'
# /var/lib/gems/1.9.1/gems/rspec-core-3.1.4/lib/rspec/core/example.rb:328:in `with_around_example_hooks'
# /var/lib/gems/1.9.1/gems/rspec-core-3.1.4/lib/rspec/core/example.rb:148:in `run'
# /var/lib/gems/1.9.1/gems/rspec-core-3.1.4/lib/rspec/core/example_group.rb:500:in `block in run_examples'
# /var/lib/gems/1.9.1/gems/rspec-core-3.1.4/lib/rspec/core/example_group.rb:496:in `map'
# /var/lib/gems/1.9.1/gems/rspec-core-3.1.4/lib/rspec/core/example_group.rb:496:in `run_examples'
# /var/lib/gems/1.9.1/gems/rspec-core-3.1.4/lib/rspec/core/example_group.rb:463:in `run'
# /var/lib/gems/1.9.1/gems/rspec-core-3.1.4/lib/rspec/core/runner.rb:111:in `block (2 levels) in run_specs'
# /var/lib/gems/1.9.1/gems/rspec-core-3.1.4/lib/rspec/core/runner.rb:111:in `map'
# /var/lib/gems/1.9.1/gems/rspec-core-3.1.4/lib/rspec/core/runner.rb:111:in `block in run_specs'
# /var/lib/gems/1.9.1/gems/rspec-core-3.1.4/lib/rspec/core/reporter.rb:53:in `report'
# /var/lib/gems/1.9.1/gems/rspec-core-3.1.4/lib/rspec/core/runner.rb:107:in `run_specs'
# /var/lib/gems/1.9.1/gems/rspec-core-3.1.4/lib/rspec/core/runner.rb:85:in `run'
# /var/lib/gems/1.9.1/gems/rspec-core-3.1.4/lib/rspec/core/runner.rb:69:in `run'
# /var/lib/gems/1.9.1/gems/rspec-core-3.1.4/lib/rspec/core/runner.rb:37:in `invoke'
# /var/lib/gems/1.9.1/gems/rspec-core-3.1.4/exe/rspec:4:in `<top (required)>'
# /usr/local/bin/rspec:23:in `load'
# /usr/local/bin/rspec:23:in `<main>'
#
# Showing full backtrace because every line was filtered out.
# See docs for RSpec::Configuration#backtrace_exclusion_patterns and
# RSpec::Configuration#backtrace_inclusion_patterns for more information.
Edit: Here is an example of one of the spec files, however, the issue comes up on about 20 spec files. I know my solutions are correct and my peers aren't having the same issues I am:
first_name = "M"
last_name = "R"
age = 23
describe 'first_name' do
it "is defined as a local variable" do
expect(defined?(first_name)).to eq 'local-variable'
end
it "is a String" do
expect(first_name).to be_a String
end
end
describe 'last_name' do
it "is defined as a local variable" do
expect(defined?(last_name)).to eq 'local-variable'
end
it "be a String" do
expect(last_name).to be_a String
end
end
describe 'age' do
it "is defined as a local variable" do
expect(defined?(age)).to eq 'local-variable'
end
it "is an integer" do
expect(age).to be_a Fixnum
end
end

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