NoMethodError: undefined method `chomp' for nil:NilClass while running Ruby Rspec on gets.chomp - ruby

This is my first post here. I'm fairly new to Ruby, especially RSpec and have been running into an issue. I have written a method that uses gets.chomp to receive a player input. However I have this method called in another method
def prompt_move
loop do
#move = gets.chomp.to_i
return move if valid_move?(move)
puts "Invalid input. Enter a column number between 1 and 7"
end
end
def valid_move?(move)
#move.is_a?(Integer) && #move.between?(1, 7)
end
def play_round
print_board
prompt_player
#move = prompt_move
end
Here is the code for my RSpec tests:
describe ConnectFour do
subject(:game) { described_class.new }
let(:player){ double(Player) }
describe '#prompt_move' do
context 'move is a valid input' do
before do
allow(game).to receive(:gets).and_return('3\n')
end
it 'returns move and stops the loop' do
error_message = 'Invalid input. Enter a column number between 1 and 7'
expect(game).to_not receive(:puts).with(error_message)
game.prompt_move
end
end
context 'when given one invalid input, then a valid input' do
before do
letter = 'a'
valid_input = '1'
allow(game).to receive(:gets).and_return(letter, valid_input)
end
it 'completes loop and displays error message once' do
error_message = 'Invalid input. Enter a column number between 1 and 7'
expect(game).to receive(:puts).with(error_message).once
game.prompt_move
end
end
end
If I remove the #prompt_move method from #play_round the tests pass without any issue. However when I try to call it from within #play_round it gives me
NoMethodError:
undefined method `chomp' for nil:NilClass
I have been struggling to figure out what is causing this error so any suggestions would be greatly appreciated!

You're executing code in your class file.
new_game = ConnectFour.new
new_game.play_game
This will run every time you load the file, like when you're testing it. It will prompt for input and run gets. What it's getting is the code of the test file (for some rspec reason). That's invalid, so it keeps running gets until eventually there is no more input and gets returns nil.
Remove that from your class file. Code like that should be in a separate file which requires the class.

Related

rspec fails even when variables should match

Methods in my class:
def get_class_info
#class_name = get_class_name
end
def get_class_name
puts "Enter the name for your class. Enter 'done' to return to the main prompt."
input = gets.chomp
if input.valid_class_name?
class_name = input.titleize
elsif input.downcase == "done"
run
else
puts "Invalid class name."
get_class_name
end
class_name
end
My test:
it "stores the name in the #class_name property" do
expect(cli.class_name).to eq('Song')
allow(cli).to receive(:gets) {'song'}
cli.get_class_info
end
It fails, saying it expected "Song" but got nil.
If I comment out the expect line and add a pry to the end of the test, querying cli.class_name returns "Song"!!!
Why is this test failing??
Update: Okay, moving the expect line to the bottom of the test apparently solved it. But I'm confused because usually the expectation goes before the actual method call. Am I wrong? What am I missing here?

Getting undefined error in mass text app

I'm creating a app that sends mass texts using a JSON file with the numbers and names. Every time I test load the app in IRB I get the error:
NameError: undefined local variable or method `data_from_file' for main:Object
from /home/qc/tep/Coding Stuff/Ruby/text app/main.rb:14:in `contacts_from_file'
I understand what the error means, but I don't understand why I'm getting the error, here's the source code:
require 'json'
def sanatize(numbers)
"+1" + number.gsub(/^1|\D/, "")
end
def numbers_from_file
file = open('numbers.json').read
JSON.parse(file)
end
def contacts_from_file
contacts= { }
data_from_file['feed']['entry'].each do |entry|
name = entry['gsx$name']['$t']
number = entry['gsx$number']['$t']
contacts[sanatize(number)] = name
end
contacts
end
def contact_numbers
contacts_from_file.keys
end
def contact_name
contacts_from_file[number]
end
And here's the JSON file:
{
'1**********' => 'Big Bird'
'1**********'} => 'Josh'
}
If anybody could help me and tell me why the data_from_file is "undefined" it would be extremely helpful, thank you ahead of time.
You never define data_from_file, you just try to read from it in the contects_from_file method.
Perhaps you meant numbers_from_file instead of data_from_file?

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.

What is Camping::Server.start invoking in /bin/camping?

I'm studying how the Camping web framework works right now, and I don't understand what the Camping::Server.start at line 10 in /bin/camping is doing.
I expected this to call the start method in /lib/camping/server.rb at line 131, and so I put a simple puts 'hello' statement at the beginning of that method, expecting that statement to be invoked when I ran /bin/camping. However, I never saw my puts statement get called, so I can only assume that it's not that start method getting called.
I feel like I'm missing something obvious here. Here is the link to the camping github page and the relevant sections of code:
Github: https://github.com/camping/camping
From /bin/camping:
#!/usr/bin/env ruby
$:.unshift File.dirname(__FILE__) + "/../lib"
require 'camping'
require 'camping/server'
begin
Camping::Server.start
rescue OptionParser::ParseError => ex
puts "did it error"
STDERR.puts "!! #{ex.message}"
puts "** use `#{File.basename($0)} --help` for more details..."
exit 1
end
From /lib/server.rb:
def start
if options[:server] == "console"
puts "** Starting console"
#reloader.reload!
r = #reloader
eval("self", TOPLEVEL_BINDING).meta_def(:reload!) { r.reload!; nil }
ARGV.clear
IRB.start
exit
else
name = server.name[/\w+$/]
puts "** Starting #{name} on #{options[:Host]}:#{options[:Port]}"
super
end
end
My puts 'hello' on Camping::Server.start wasn't getting called because I didn't understand how static methods were defined in ruby.
start was being called statically, and I realize now that the start method I was looking at in the snippet wasn't a static method, which meant that another start method was getting called. I looked into Camping::Server and realized that it inherited from Rack::Server, which has the following method:
def self.start(options = nil)
new(options).start
end
That was the method getting called, not the one on /lib/camping/server.rb. I had been looking at the wrong method.

as_null_object not passing with two inputs

I'm working through the RSpec Book, and I have the following test code:
require 'spec_helper'
module Codebreaker
describe Game do
describe "#start" do
let(:output) { double('output').as_null_object }
let(:game) { Game.new(output) }
it "sends a welcome message" do
output.should_receive(:puts).with('Welcome to Codebreaker!')
game.start
end
it "prompts for the first guess" do
output.should_receive(:puts).with('Enter guess:')
game.start
end
end
end
end
which corresponds to the following code:
module Codebreaker
class Game
def initialize(output)
#output = output
end
def start
#output.puts 'Welcome to Codebreaker!'
#output.puts 'Enter a guess:'
end
end
end
Since I've set :output up as a double.as_null_object, I expect it to ignore any arguments/methods it is not expecting. For the first test (sends a welcome message), that's what it does, and it passes. The second test, however, is giving me this error:
Failure/Error: output.should_receive(:puts).with('Enter guess:')
Double "output" received :puts with unexpected arguments
expected: ("Enter guess:")
got: ("Welcome to Codebreaker!"), ("Enter a guess:")
# ./spec/codebreaker/game_spec.rb:16:in `block (3 levels) in <module:Codebreaker>'
Why is the double returning both "Welcome to Codebreaker!" and "Enter a guess" when I have explicitly told it to only expect "Enter a guess:", and how can I fix this while maintaining this same setup/structure?
The second case is failing because you have a typo in your expectation. You meant Enter a guess: instead of Enter guess:.
Unfortunately, rspec is very picky about wording on strings. In your start method you wrote "Enter guess" instead of "Enter a guess:".
It's important to follow the wording to a T, when you start having to raise an error, rspec gives you a very nasty response.
Good luck! Rspec is a great tool as you get further into it.

Resources