Adding object to array of arrays - ruby

I am trying to add an object to an array of arrays, but when i do, i am recieving an error in my array of array unit tests, stating :- "undefined method 'has_key' for nil:NilClass". However, if i try and add a string or number to the array of array, it works absolutely fine.
I set up my array of arrays like this
#array_of_array= Array.new(5) { Array.new(3) }
Now if I try to do this
#array_of_array[0][0] = MyObject.new
Then if I run my unit tests against #array_of_array, i get the error.
But if I try to do this
#array_of_array[0][0] = 'Test'
Theres no problem.
--Edited---
Heres failing test
it "should place object in correct starting position" do
array_of_array= Array.new(5) { Array.new(3) }
array_of_array[1][0] = MyObject.new
array_of_array.should eql('fail on purpose..want to see output')
end
Im new to ruby, so unsure of where im going wrong. Thanks

Like Claw said, the error probably means that your MyObject.new statement is returning a nil object for some reason. Then you're trying to call the function 'has_key' of that nil object.
Does your MyObject class throw an exception if you use .new! instead of .new ? If so, you could see why it's failing to return a proper MyObject object.
Edit
To catch an exception inside your 'new' method for the MyObject model, you could do something like:
def new
begin
#whatever is done in this method
rescue => exception
puts exception.message
end
end

Related

Rspec error in ruby code testing

Rspec code is
it "calls calculate_word_frequency when created" do
expect_any_instance_of(LineAnalyzer).to receive(:calculate_word_frequency)
LineAnalyzer.new("", 1)
end
Code of class is
def initialize(content,line_number)
#content = content
#line_number = line_number
end
def calculate_word_frequency
h = Hash.new(0)
abc = #content.split(' ')
abc.each { |word| h[word.downcase] += 1 }
sort = h.sort_by {|_key, value| value}.reverse
puts #highest_wf_count = sort.first[1]
a = h.select{|key, hash| hash == #highest_wf_count }
puts #highest_wf_words = a.keys
end
This test gives an error
LineAnalyzer calls calculate_word_frequency when created
Failure/Error: DEFAULT_FAILURE_NOTIFIER = lambda { |failure, _opts| raise failure }
Exactly one instance should have received the following message(s) but didn't: calculate_word_frequency
How I resolve this error.How I pass this test?
I believe you were asking "Why do I get this error message?" and not "Why does my spec not pass?"
The reason you're getting this particular error message is you used expect_any_instance_of in your spec, so RSpec raised the error within its own code rather than in yours essentially because it reached the end of execution without an exception, but without your spy being called either. The important part of the error message is this: Exactly one instance should have received the following message(s) but didn't: calculate_word_frequency. That's why your spec failed; it's just that apparently RSpec decided to give you a far less useful exception and backtrace.
I ran into the same problem with one of my specs today, but it was nothing more serious than a failed expectation. Hopefully this helps clear it up for you.
The entire point of this test is to insure that the constructor invokes the method. It's written very clearly, in a very straight forward way.
If you want the test to pass, modify the constructor so it invokes the method.

how do I use rspec to test instance methods in ruby?

I have an instance method that would be invoked after creating a new instance of the class.
How do I test it in Rspec? I use the following and get an error:
let(:schedule) { ScheduleKaya.new('test-client-id') }
let(:schedule) { schedule.create_recurring_event('test-keyword', 'slack') }
In other words, I want to create the instance. Then I want to apply a method create_recurring_event.
My test wants to check if it assigned the variables to the instance.
it "has #keyword = test-keyword" do
expect(schedule.keyword).to eq('test-keyword')
end
Because it makes a database call, I want to check the response back from the call to see if I get a status = 200.
But I can't seem to both create the instance and then apply the method.
Question:
What is the right way to test for an instance method, one that is applied after creating a new instance.
A let block acts like a method and returns the return value of the last statement. Therefore just write both into the same block and ensure that the right value is returned:
let(:schedule) do
schedule_kaya = ScheduleKaya.new('test-client-id')
schedule_kaya.create_recurring_event('test-keyword', 'slack')
schedule_kaya
end
Or you can use tap:
let(:schedule) do
ScheduleKaya.new('test-client-id').tap do |schedule_kaya|
schedule_kaya.create_recurring_event('test-keyword', 'slack')
end
end
I suggest FactoryGirl together with Rspec, if you are on Railsfactory_girl_rails, looks like below:
it "has #keyword = test-keyword" do
schedule = Factory(:shcedule, keyword: "has #keyword = test-keyword")
expect(schedule.keyword).to eq('test-keyword')
end

What object do I need to respond to .map(&:key)? (ruby)

I'm doing a code challenge, and know the message I need my code to respond to.
I also know I have the correct data in my object to pass the test, I just can't seem to get the format correct.
The test is
class.method.map(&:name)
Which should return an array of names that the method returns.
I have tried having my method return a hash with :name as a key and an array containing the hash but neither work, I'm getting this error
rb:82:in `each': undefined method `name' for [:name, "Name I want returned"]:Array
What do I need to do to respond to the map call correctly?
class.method.map(&:name) means
class.method.map do |instance|
instance.name
end
So basically your method needs to return a enumeration of objects, which has a method named name.

Does should_receive do something I don't expect?

Consider the following two trivial models:
class Iq
def score
#Some Irrelevant Code
end
end
class Person
def iq_score
Iq.new(self).score #error here
end
end
And the following Rspec test:
describe "#iq_score" do
let(:person) { Person.new }
it "creates an instance of Iq with the person" do
Iq.should_receive(:new).with(person)
Iq.any_instance.stub(:score).and_return(100.0)
person.iq_score
end
end
When I run this test (or, rather, an analogous one), it appears the stub has not worked:
Failure/Error: person.iq_score
NoMethodError:
undefined method `iq_score' for nil:NilClass
The failure, as you might guess, is on the line marked "error here" above. When the should_receive line is commented out, this error disappears. What's going on?
Since RSpec has extended stubber functionality, now following way is correct:
Iq.should_receive(:new).with(person).and_call_original
It will (1) check expectation (2) return control to original function, not just return nil.
You're stubbing away the initializer:
Iq.should_receive(:new).with(person)
returns nil, so Iq.new is nil. To fix, just do this:
Iq.should_receive(:new).with(person).and_return(mock('iq', :iq_score => 34))
person.iq_score.should == 34 // assert it is really the mock you get

How to use yield self within Rspec

This is a description of how to create a helper method in Rspec taken from the Rspec book (page 149). This example assumes that there is a method called 'set_status' which is triggered when the 'Thing' object is created.
Both sets of code create a new 'Thing' object, set the status, then do 'fancy_stuff'. The first set of code is perfect clear to me. One of the 'it' statements it triggered, which then calls the 'create_thing' method with options. A new 'Thing' object is created and the 'set_status' method is called with the 'options' attribute as the parameter.
The second set of code is similar. One of the 'it' statements is triggered, which then calls the 'given_thing_with' method while passing ':status' hash assignment as a parameter. Within the 'given_thing_with' method the 'yield' is triggered taking the 'Thing.new' as a parameter. This is where I am having trouble. When I try to run this code I get an error of "block given to yield". I understand that whatever attributes that are passed by yield will be returned to the 'thing' in pipe brace from the 'it' statement that called the 'given_thing_with' method. I can get the new
What I don't understand is why the code block is not called in the 'given_thing_with' method after the 'yield' command. In other words, I can't code in that block to run.
Thanks in advance for your help.
The remainder of this question is quoted directly from the Rspec book:
describe Thing do
def create_thing(options)
thing = Thing.new
thing.set_status(options[:status])
thing
end
it "should do something when ok" do
thing = create_thing(:status => 'ok')
thing.do_fancy_stuff(1, true, :move => 'left', :obstacles => nil)
...
end
it "should do something else when not so good" do
thing = create_thing(:status => 'not so good')
thing.do_fancy_stuff(1, true, :move => 'left', :obstacles => nil)
...
end
end
One idiom you can apply to clean this up even more is to yield self from initializers in your objects. Assuming that Thing's initialize() method does this and set_status() does as well, you can write the previous like this:
describe Thing do
def given_thing_with(options)
yield Thing.new do |thing|
thing.set_status(options[:status])
end
end
it "should do something when ok" do
given_thing_with(:status => 'ok') do |thing|
thing.do_fancy_stuff(1, true, :move => 'left', :obstacles => nil)
...
end
end
it "should do something else when not so good" do
given_thing_with(:status => 'not so good') do |thing|
thing.do_fancy_stuff(1, true, :move => 'left', :obstacles => nil)
...
end
end
end
The example in the book is a bit confusing because the implementation of Thing is not shown. To make this work you need to write Thing like so:
class Thing
def initialize
yield self
end
end
When given_thing_with is called it yields a new Thing, which will yield itself when it is constructed. This means that when the inner code block (the one containing thing.set_status) is executed it will have a reference to he newly built Thing.
There are 2 issues with the code from book.
1. Setting up the initializer to yield itself
When the Thing object is created, it needs an initializer and need yield itself.
class Thing
def initialize
yield self
end
end
However, this alone will still causes an error, at least on my system, which is Ruby 1.9.3. Specifically, the error is 'block given to yield (SyntaxError)'. This doesn't make much sense, since that is what we want it to do. Regarless, that is the error I get.
2. Fixing the 'block given to yield' error
This is not as obvious and has something to do with either Ruby or the 'yield' statement, but creating a block using 'do...end' as was written in the book and is shown below causes the error.
yield Thing.new do |thing|
thing.set_status(options[:status])
end
Fixing this error is simlpy a matter of creating the block using braces, '{...}', as is shown below.
yield Thing.new { |thing|
thing.set_status(options[:status])
}
This is not good form for multiline Ruby code, but it works.
Extra. How the series of yields works to set the parameters of the 'Thing' object
The problem is already fixed, but this explains how it works.
the "caller block" calls 'given_thing_with' method with a parameter
that method yields back to the "caller block" a new "Thing" and a block (I'll call it the "yield block")
to execute the "yield block", the Thing class needs the initialization and 'yield self', otherwise the 'set_status' method will never be run because the block will be ignored
the new "Thing" is already in the "caller block" and has it's status set and now the relevant method is executed

Resources