rspec double can't be created within a before all block - ruby

This is very weird. The following code:
describe "Spike" do
before(:all) do
something = double('name')
end
describe "a test" do
it "is basic" do
1.should == 1
end
end
end
Fails with:
NoMethodError: undefined method `double' for #<RSpec::Core::ExampleGroup::Nested_1:0x9dec5e8 #__memoized=nil>
./spec/unit/whatever/spike_spec.rb:3:in `block (2 levels) in '
Change the before(:all) to before(:each) and everything is fine. I'm using Ruby 1.9.3
Any ideas?

This is expected behavior, since doubles get cleaned out after every example. You should stick with using these in a before(:each) block.
See https://www.relishapp.com/rspec/rspec-mocks/docs/scope
Also see https://github.com/rspec/rspec-core/issues/202 for discussion on this.

Related

Can't understand why I'm getting a `initialize': uninitialized constant Controller::View (NameError)

I'm trying to understand why I'm getting this error and I suspect it's because I have my Controller class and View class in two separate Ruby files. I was told that using require_relative 'filename' should reference all the code from one file into another, but I seem to be missing something. Okay here goes,
In controller.rb file, I have
require_relative 'view'
require_relative 'deck_model'
require_relative 'flashcard_model'
class Controller
def initialize
#deckofcards = Deck.new
#welcome = View.new.welcome
#player_guess = View.new.get_user_guess
#success_view = View.new.success
#failure_view = View.new.failure
end
def run
#Logic to run the game
# #current_card
# #user_guess
puts "Let's see if this prints"
# pull_card_from_deck
end
end
In my view.rb file, I have,
require_relative 'controller'
class View
attr_accessor :userguess
def initialize (userguess = " ")
#userguess = userguess
end
def welcome
system ("clear")
puts "Welcome! Let's play a game."
puts "I'll give you a definition and you have to give me the term"
puts "Ready..."
end
def get_user_guess
#userguess = gets.chomp.downcase
end
def success
puts "Excellent! You got it."
end
def failure
puts "No, that's not quite right."
end
end
However when I run controller.rb, I get the following error,
/Users/sean/Projects/flash/source/controller.rb:11:in `initialize': uninitialized constant Controller::View (NameError)
from /Users/sean/Projects/flash/source/controller.rb:51:in `new'
from /Users/sean/Projects/flash/source/controller.rb:51:in `<top (required)>'
from /Users/sean/Projects/flash/source/view.rb:1:in `require_relative'
from /Users/sean/Projects/flash/source/view.rb:1:in `<top (required)>'
from controller.rb:1:in `require_relative'
from controller.rb:1:in `<main>'
Can anyone please help me figure this out.
You did not post your full code, but it sounds like this is an error caused by the circular dependencies you specified in your project. You have view.rb depending on controller.rb and controller.rb depending on view.rb. The Ruby interpreter will not execute these files simultaneously; it has to execute one and then execute the other.
It looks like it is executing controller.rb first, but it sees that view.rb is required, so it starts executing that. Then in view.rb it sees that controller.rb is required, so it starts executing controller.rb again. Then at some point in controller.rb, you must be creating a new instance of the Controller class. But we aren't done defining the View class yet, so View is undefined and you get an exception while trying to create that controller.
To fix this, you should consider not creating any Controller or View objects until both of the classes are fully loaded.
+1 to #DavidGrayson comment.
If my assumption is correct, your issue is with require_relative 'controller' in your view.rb file.
If you see, it looks like View is requiring Controller then Controller gets loaded which seems to be sending new somewhere to Controller which then sends new to View but it hasn't been completely required.

Rspec any_instance.stub raises undefined method `any_instance_recorder_for' for nil:NilClass exception

Here is the class that I'm testing contained in Foo.rb:
class Foo
def bar
return 2
end
end
Here is the my test contained in Foo_spec.rb:
require "./Foo.rb"
describe "Foo" do
before(:all) do
puts "#{Foo == nil}"
Foo.any_instance.stub(:bar).and_return(1)
end
it "should pass this" do
f = Foo.new
f.bar.should eq 1
end
end
I am getting the following output:
false
F
Failures:
1) Foo Should pass this
Failure/Error: Foo.any_instance.stub(:bar).and_return(1)
NoMethodError:
undefined method `any_instance_recorder_for' for nil:NilClass
# ./Foo_spec.rb:6:in `block (2 levels) in <top (required)>'
Finished in 0 seconds
1 example, 1 failure
Failed examples:
rspec ./Foo_spec.rb:9 # Foo Should pass this
I've consulted the doc and the example given is passing on my machine (so it isn't a problem with the rspec code), but it isn't giving me any information on what I might be doing wrong. The error message is also quite confusing as it's telling me not to call .any_instance on a nil:NilClass, but as I proved with my output, Foo isn't nil. How am I supposed to call .any_instance.stub on my custom object?
I'm using Ruby 1.9.3 and rspec 2.14.5.
You should use before(:each) for stubbing.
Stubs in before(:all) are not supported. The reason is that all stubs and mocks get cleared out after each example, so any stub that is set in before(:all) would work in the first example that happens to run in that group, but not for any others.
rspec-mocks readme
From Rspec 3 any_instance is not defined anymore.
Now use:
allow_any_instance_of(Foo).to receive(:bar).and_return(1)
Source for this and older versions:
https://makandracards.com/makandra/2561-stub-methods-on-any-instance-of-a-class-in-rspec-1-and-rspec-2
Updating rspec worked for me. You can do it using the following command:
bundle update rspec

In RSpec, using let to assign a regex creates unexpected pass/fail behavior - Bug or user error?

File with object under test: foo.rb
class Foo
def a_string
"abcdef8"
end
end
Spec file: foo_spec.rb
require_relative "./foo"
describe Foo do
let(:foo) {Foo.new}
let(:my_matcher) {/^[a-z]+(\d)$/}
# This test passes
it "should match and pass" do
my_str = foo.a_string
my_matcher # <--- why does this affect the test?
matcher = my_str.match(my_matcher)
8.should == matcher[1].to_i
end
# This test fails
it "should also match and pass but fails" do
my_str = foo.a_string
#my_matcher #<---- the only change between the tests
matcher = my_str.match(my_matcher) #<---- when called here, it behaves differently
8.should == matcher[1].to_i
end
end
rspec foo_spec.rb
.F
Failures:
1) Foo should also match and pass but fails
Failure/Error: 8.should == matcher[1].to_i
NoMethodError:
undefined method `[]' for /^[a-z]+(\d)$/:Regexp
# ./foo_spec.rb:18:in `block (2 levels) in <top (required)>'
Finished in 0.00095 seconds
2 examples, 1 failure
Failed examples:
rspec ./foo_spec.rb:14 # Foo should also match and pass but fails
The only difference in the two tests is whether my_matcher is invoked. I first noticed this problem when I was inspecting my_matcher (i.e. p my_matcher), but it also occurs with just invoking my_matcher.
Is this a bug, or am I doing something wrong? Maybe it has something to do with capturing Regex data?
It seems incredibly odd behavior, especially for ruby.
For what its worth, it's an easy (if slightly less DRY) fix. If my_matcher is declared in the it block it works as expected.
That looks like a bug. Can you file an issue with rspec-core?

ArgumentError in rspec

I want to write some tree data structure in ruby. The class file:
class Tree
attr_accessor :node, :left, :right
def initialize(node, left=nil, right=nil)
self.node=node
self.left=left
self.right=right
end
end
The rspec file:
require 'init.rb'
describe Tree do
it "should be created" do
t2=Tree.new(2)
t1=Tree.new(1)
t=Tree.new(3,t1,t2)
t.should_not be nil
t.left.node should eql 1
t.right.node should eql 2
end
end
Rspec keeps complaining:
1) Tree should be created
Failure/Error: t.left.node should eql 1
ArgumentError:
wrong number of arguments (0 for 1)
# ./app/tree.rb:3:in `initialize'
# ./spec/tree_spec.rb:9:in `block (2 levels) in <top (required)>'
Why?? I move the spec code into the class file and it works out. What is wrong?
Believe it or not, the problem is two missing dots in your rspec. These lines:
t.left.node should eql 1
t.right.node should eql 2
should be this:
t.left.node.should eql 1
t.right.node.should eql 2
Insert that period before should, and your spec should pass.
Here's what's going on. The should method works on any value, but if you call it bare, like this:
should == "hello"
it will operate on the subject of your test. What's the subject? Well, you can set the subject to whatever you want using the subject method, but if you don't, rspec will assume the subject is an instance of whatever class is being described. It sees this at the top of your spec:
describe Tree
and tries to create a subject like this:
Tree.new
which blows up, since your initialize won't work without any arguments; it needs at least one. The result is a pretty cryptic error if you didn't intend to write a should with an implicit subject.

Weird error when trying to test method with argument in Mocha. Is it a bug or is it me?

It's rather hard to find any documentation on Mocha, so I'm afraid I'm totally at sea here. I have found a problem with stubbing methods that pass arguments. So for instance if I set up a class like this:
class Red
def gets(*args)
#input.gets(*args)
end
def puts(*args)
#output.puts(*args)
end
def initialize
#input = $stdin
#output = $stdout
end
private
def first_method
input = gets.chomp
if input == "test"
second_method(input)
end
end
def second_method(value)
puts value
second_method(value)
end
end
Yes it's contrived, but it's a simplification of the idea that you may have a method that you don't want called in the test.
So I might write a test such as:
setup do
#project = Red.new
#project.instance_variable_set(:#input, StringIO.new("test\n"))
#project.stubs(:second_method)
end
should "pass input value to second_method" do
#project.expects(:second_method).with("test").once
#project.instance_eval {first_method}
end
Now I would expect this to pass. But instead I get this rather arcane error message:
Errno::ENOENT: No such file or directory - getcwd
/Users/i0n/.rvm/gems/ruby-1.9.2-head/gems/mocha-0.9.8/lib/mocha/backtrace_filter.rb:12:in `expand_path'
/Users/i0n/.rvm/gems/ruby-1.9.2-head/gems/mocha-0.9.8/lib/mocha/backtrace_filter.rb:12:in `block in filtered'
/Users/i0n/.rvm/gems/ruby-1.9.2-head/gems/mocha-0.9.8/lib/mocha/backtrace_filter.rb:12:in `reject'
/Users/i0n/.rvm/gems/ruby-1.9.2-head/gems/mocha-0.9.8/lib/mocha/backtrace_filter.rb:12:in `filtered'
/Users/i0n/.rvm/gems/ruby-1.9.2-head/gems/mocha-0.9.8/lib/mocha/expectation_error.rb:10:in `initialize'
/Users/i0n/.rvm/gems/ruby-1.9.2-head/gems/mocha-0.9.8/lib/mocha/mockery.rb:53:in `new'
/Users/i0n/.rvm/gems/ruby-1.9.2-head/gems/mocha-0.9.8/lib/mocha/mockery.rb:53:in `verify'
/Users/i0n/.rvm/gems/ruby-1.9.2-head/gems/mocha-0.9.8/lib/mocha/api.rb:156:in `mocha_verify'
/Users/i0n/.rvm/gems/ruby-1.9.2-head/gems/mocha-0.9.8/lib/mocha/integration/mini_test/version_131_and_above.rb:27:in `run'
This means absolutely nothing to me, other than something deep in Mochas bowels has just gone clang. If I write the same sort of test without an argument passing to the second method I get no problem. Am I missing something?
I think it must be something in shoulda causing the problem. I use test/unit, and everything appears to be OK.
require 'rubygems'
require "test/unit"
require 'mocha'
require File.dirname(__FILE__) + '/../src/red'
class RedTest < Test::Unit::TestCase
def setup
#project = Red.new
#project.instance_variable_set(:#input, StringIO.new("test\n"))
#project.stubs(:second_method)
end
def test_description_of_thing_being_tested
#project.expects(:second_method).with("test").once
#project.instance_eval {first_method}
end
end
gives the following output:
stephen#iolanta:~/tmp/red/test # ruby red_test.rb
Loaded suite red_test
Started
.
Finished in 0.000679 seconds.
1 tests, 1 assertions, 0 failures, 0 errors
stephen#iolanta:~/tmp/red/test #
Sorry - I've only just seen this. It's better to submit bug reports to us in Lighthouse. What documentation have you found? Have you seen the RDoc on Rubyforge? What sort of documentation were you looking for that you did not find?
I've been unable to reproduce your bug. What version of Ruby, Rubygems, Shoulda & Mocha were you using?
You can see the results of me running your test in this Gist.

Resources