Reputation: 421
I'm only a few days into learning rspec, and I'm trying to write my first test in a program that contains classes. I know this test is wrong, but I don't know how to fix it because I don't get a failure. Instead, it just starts running through my program (a simple tic tac toe game). I left out the code for the tic tac toe game for brevity. Any guidance would be greatly appreciated. Thanks!
require "tictactoe"
describe Game do
describe "#players" do
it "displays player names" do
player1 = "Harry"
expect(Game.new("Harry", "Nick").players).to eq(player1)
end
end
end
Upvotes: 0
Views: 355
Reputation: 106027
As we discovered in the comments above, the problem is that tictactoe.rb
has the code that runs your entire program, so require "tictactoe"
also runs your entire program.
There are two solutions.
The first is to change tictactoe.rb
to only execute the code that causes the entire program to run when your script is executed from the command line and not when it's require
d from another script. This is a common idiom in Ruby:
# declare your classes up here
class Game
# ...
end
# etc...
# down here run the program only if this
# script is run from the command line
if __FILE__ == $0
game = Game.new
# ...and so on...
end
Now you can require "tictactoe"
in your tests, knowing that the code in the if
block won't be executed.
The second solution is to move your class declarations into other files, e.g. put the Game class in game.rb
and have tictactoe.rb
do require "game"
, and have the RSpec code that tests the Game class do the same.
The latter approach is more maintainable as programs get larger. If you look at a large gem like, say, Bundler, you'll find that the "program" file, bundle
only has a few lines of code—all it does is require
other code that does the real work.
However, if your program is small and you don't anticipate it growing much in the short term, the former approach is just fine, too.
Upvotes: 2
Reputation: 2005
Try this. First, require rspec
at the top of your file.
require "tictactoe"
require "rspec"
RSpec.describe Game do
describe "#players" do
it "displays player names" do
player1 = "Harry"
expect(Game.new("Harry", "Nick").players).to eq(player1)
end
end
end
Then make sure you run your file with rspec
NOT ruby
so
rspec foo.rb
Upvotes: 0