Pure Ruby rspec test passes without method being defined - ruby

I have an rspec test on a pure Ruby model:
require 'spec_helper'
require 'organization'
describe Organization do
context '#is_root?' do
it "creates a root organization" do
org = Organization.new
expect { org.is_root?.to eq true }
end
end
end
My organization model looks like this:
class Organization
attr_accessor :parent
def initialize(parent = nil)
self.parent = parent
end
end
The output when running the tests:
bundle exec rspec spec/organization_spec.rb:6
Run options: include {:locations=>{"./spec/organization_spec.rb"=>[6]}}
.
Finished in 0.00051 seconds
1 example, 0 failures
When I run the test, it passes, despite the fact that the method is_root? doesn't exist on the model. I usually work in Rails, not pure Ruby, and I've never seen this happen. What is going on?
Thanks!

It should be:
expect(org.is_root?).to eq true
When you pass block to expect it is being wrapped in ExpectationTarget class (strictly speaking BlockExpectationTarget < ExpectationTarget). Since you didn't specify what you expect from this object, the block is never executed, hence no error is raised.

You are passing a block to expect, which is never being called. You can see this by setting an expectation on that block
expect { org.is_root?.to eq true }.to_not raise_error
1) Organization#is_root? creates a root organization
Failure/Error: expect { puts "HI";org.is_root?.to eq true }.to_not raise_error
expected no Exception, got #<NoMethodError: undefined method `is_root?' for #<Organization:0x007ffa798c2ed8 #parent=nil>> with backtrace:
# ./test_spec.rb:15:in `block (4 levels) in <top (required)>'
# ./test_spec.rb:15:in `block (3 levels) in <top (required)>'
# ./test_spec.rb:15:in `block (3 levels) in <top (required)>'
Or by just putting a plain raise or puts inside the block, neither of which will be called:
expect { puts "HI"; raise; org.is_root?.to eq true }
The block form is used for expecting that a piece of code raises an exception or not. The correct syntax for checking values is:
expect(org.is_root?).to eq(true)

Related

Rspec validation of method definition - Failure/Error

In Rspec, testing whether an instance is able to call method x.
DockingStation.rb
class DockingStation
def release_bike
end
end
Docking_spec.rb
require_relative '../lib/DockingStation'
describe DockingStation do
before(:each) do
#dockstat = DockingStation.new
end
describe "#DockingStation" do
it "Check release method" do
expect(#dockstat).to respond_to(:release_bike)
end
end
end
Currently getting the following error message:
1) DockingStation#DockingStation Check release method
Failure/Error: expect(#dockstat).to respond_to(:release_bike)
expected #<DockingStation:0x007fa518a6da00> to respond to :release_bike
# ./spec/Docking_spec.rb:10:in `block (3 levels) in <top (required)>'
What I'm expecting is for the object #dockstat instantiated in the Docking_spec.rb to respond to the release_bike method defined in DockingStation.rb, but this is not the case.
require_relative '../DockingStation'

If I'm testing an rspec extension, how do I suppress the results of tests which fail as part of the test?

I'm trying to write specs for an extension to rspec.
This is the gist of what I'm trying to test:
require 'rspec-let-and-after-extension'
RSpec.describe "let(...).and_after" do
it 'is called if the `let` is invoked even if the example fails' do
call_order = []
RSpec.describe do
let(:foo) { }.and_after { call_order << :and_after }
it { foo; call_order << :example; raise 'failed!' }
end.run
expect(call_order).to eq [:example, :and_after]
end
end
One of the important behaviours is that if running the example fails, the cleanup code still runs. So I test this by recording the order of the calls and raising an exception from the example.
Problem is, when I run it, it sees this block as a second example, which then fails with errors:
.F
Failures:
1)
Got 0 failures and 2 other errors:
1.1) Failure/Error: it { foo; call_order << :example; raise 'failed!' }
RuntimeError:
failed!
# ./spec/spec.rb:43:in `block (4 levels) in <top (required)>'
# ./spec/spec.rb:44:in `block (2 levels) in <top (required)>'
1.2) Failure/Error: it { foo; call_order << :example; raise 'failed!' }
RuntimeError:
failed!
# ./spec/spec.rb:43:in `block (4 levels) in <top (required)>'
Finished in 0.00167 seconds (files took 0.08011 seconds to load)
2 examples, 1 failure
Failed examples:
rspec ./spec/spec.rb:43 #
As you can see, the output did have one dot, so the actual example passed. But then there is an F, because it has seen the internal example, run that, and unsurprisingly that one failed.
How do I make rspec not see this nested example as one of the examples it's supposed to run, so that this example completes with a single dot?
(If you're wondering about what the rspec devs themselves do about their tests, it looks like they use cucumber. Do they use cucumber because they couldn't figure this out either? :))
You can use the new sandboxing API (available in 3.2+).
RSpec.configure do |rspec|
rspec.around do |ex|
RSpec::Core::Sandbox.sandboxed do |config|
# re-configure any configuration defined by your extension here
# before allowing the example to run. The sandbox runs with a fresh
# config instance, which means any configuration you have set in
# `rspec-let-and-after-extension` will not apply while the example
# is running.
# config.extend MyExtensionModule
ex.run
end
end
end

Ruby script raising unexpected backtrace

I have a method that should raise a custom error with a message. When I catch the error and raise my own custom error, it is still raising and printing the backtrace of the original error. I just want the custom error and message. Code below.
Method:
def load(configs)
begin
opts = {access_token: configs['token'],
api_endpoint: configs['endpoint'],
web_endpoint: configs['site'],
auto_paginate: configs['pagination']}
client = Octokit::Client.new(opts)
repos = client.org_repos(configs['org'])
repos.each do |r|
Project.create(name: r.name)
end
rescue Octokit::Unauthorized
raise GitConfigError, "boom"
end
#rescue Octokit::Unauthorized
end
class GitConfigError < StandardError
end
My test (which is failling):
context 'with incorrect git configs' do
before do
allow(loader).to receive(:load).and_raise Octokit::Unauthorized
end
it { expect{loader.load(configs)}.to raise_error(GitConfigError, "boom" ) }
end
Test Output:
GitProjectLoader#load with incorrect git configs should raise GitConfigError with "boom"
Failure/Error: it { expect{loader.load(configs)}.to raise_error(GitConfigError, "boom" ) }
expected GitConfigError with "boom", got #<Octokit::Unauthorized: Octokit::Unauthorized> with backtrace:
# ./spec/lib/git_project_loader_spec.rb:24:in `block (5 levels) in <top (required)>'
# ./spec/lib/git_project_loader_spec.rb:24:in `block (4 levels) in <top (required)>'
# ./spec/lib/git_project_loader_spec.rb:24:in `block (4 levels) in <top (required)>'
If you intend to test the handling of the Octokit::Unauthorized error, then raise the error anywhere before the rescue kicks in. Preferably, someplace where it would actually be raised.
Something like this, for example:
before do
allow(Octokit::Client).to receive(:new).and_raise(Octokit::Unauthorized)
end
And then:
expect{ loader.load(configs) }.to raise_error(GitConfigError, "boom" )
As a side note, I would discourage enclosing all lines of your method in a begin;rescue;end structure; you should enclose only the lines from which you are expecting errors.
You are not testing your code as you think. You have mocked it out.
The line
allow(loader).to receive(:load).and_raise Octokit::Unauthorized
replaces the load method on loader with a stub which just raises the named error.
Remove your before block, and it should test your code as intended. Note as written it will make a real request via Octokit, unless you mock that out instead.

Rspec 3 vs Rspec 2 matchers

Learning how to Rspec 3. I have a question on the matchers. The tutorial i am following is based on Rspec 2.
describe Team do
it "has a name" do
#Team.new("Random name").should respond_to :name
expect { Team.new("Random name") }.to be(:name)
end
it "has a list of players" do
#Team.new("Random name").players.should be_kind_of Array
expect { Team.new("Random name").players }.to be_kind_of(Array)
end
end
Why is the code causing an error while the one i commented out passing with depreciation warning.
Error
Failures:
1) Team has a name
Failure/Error: expect { Team.new("Random name") }.to be(:name)
You must pass an argument rather than a block to use the provided matcher (equal :name), or the matcher must implement `supports_block_expectations?`.
# ./spec/team_spec.rb:7:in `block (2 levels) in <top (required)>'
2) Team has a list of players
Failure/Error: expect { Team.new("Random name").players }.to be_kind_of(Array)
You must pass an argument rather than a block to use the provided matcher (be a kind of Array), or the matcher must implement `supports_block_expectations?`.
# ./spec/team_spec.rb:13:in `block (2 levels) in <top (required)>'
You should use normal brackets for those tests:
expect(Team.new("Random name")).to eq :name
When you use curly brackets, you are passing a block of code. For rspec3 it means that you will put some expectations about the execution of this block rather than on the result of execution, so for example
expect { raise 'hello' }.to raise_error
EDIT:
Note however that this test will fail, as Team.new returns an object, not a symbol. You can modify your test so it passes:
expect(Team.new("Random name")).to respond_to :name
# or
expect(Team.new("Random name").name).to eq "Random name"

"ArgumentError: wrong number of arguments (2 for 0)" though method requires two parameters

I have a MiniTest like this:
describe Message do
describe "#is_getting_unavailable" do
let( :message ) { Message.new() }
it "should be false when user does not exist in the database" do
message.handle
assert_equal(false, message.is_getting_unavailable)
end
end
end
Running this gives me complaint from assert_equal:
Message::#is_getting_unavailable#test_0001_should be false when user does not exist in the database
ArgumentError: wrong number of arguments (2 for 0)
test/unit/message_test.rb:148:in `(root)'
org/jruby/RubyBasicObject.java:1703:in `__send__'
org/jruby/RubyKernel.java:2209:in `send'
org/jruby/RubyArray.java:1617:in `each'
org/jruby/RubyArray.java:1617:in `each'
I did not understand this, so I included the test (just before the call of assert_equal):
puts method(:assert_equal).inspect
puts method(:assert_equal).arity
puts method(:assert_equal).source_location.inspect
The output is:
#<Method: #<Class:0x1d1e394d>(Minitest::Assertions)#assert_equal>
-3
["/home/rjung/.rvm/gems/jruby-1.7.4/gems/minitest-5.0.6/lib/minitest/assertions.rb", 155]
So the method is correct, and the arity is correct. What's the issue here?
We also use rr, timecop. Any other questions, that could help me find a solution?
It took me a while, but I could narrow the problem down to this failing test:
require 'minitest/autorun'
describe 'Message' do
let( :message ) { Hash.new }
it "should not fail awkwardly" do
assert_equal false, message.nil?
end
end
The output of this test is
1) Error:
Message#test_0001_should not fail awkwardly:
ArgumentError: wrong number of arguments (2 for 0)
test/unit/message_test.rb:7:in `(root)'
org/jruby/RubyBasicObject.java:1703:in `__send__'
org/jruby/RubyKernel.java:2209:in `send'
org/jruby/RubyArray.java:1617:in `each'
org/jruby/RubyArray.java:1617:in `each'
So I filed a Bug for https://github.com/seattlerb/minitest/issues/343.
Minitest does have a method message that was overwritten, so don't use message as a variable.
What I still wonder is, why the stacktrace says the wrong number of arguments happen in message_test.rb:7, because the method that takes no arguments (message) is definitive called from somewhere else.

Resources