RSpec for File.read()

How can express the RSpec example to the code?

def reader
words = File.read(‘filename’).scan(/\w+/)
end

I am pretty new to Ruby, so maybe this isn’t the greatest advise.

I would split that method into two, one to read the contents of the
file, and another that extracts the words from a string:

def read_file( file_name )
File.read( file_name )
end

def find_words( str )
str.scan( /\w+/ )
end

Now you can test by creating a file with specific contents and assert
that read_file() returns the contents. The file you created can be
deleted. You can test the second method by giving it a string and
asserting that an array of the words is returned.

You can then be sure that something like this works as intended:

find_words( read_file( ‘my_file.txt’ ) )

No need to split the method implementation.

describe “#reader” do
it “returns word characters only” do
File.stub(:read).and_return(“hello, world”)
expect(reader.size).to eq(2)
expect(reader).to include(“hello”)
expect(reader).not_to include(’,’)
end
end

https://www.relishapp.com/rspec/rspec-mocks/v/3-0/docs/method-stubs/stub-with-a-simple-return-value

Vlad M_ wrote in post #1146058:

No need to split the method implementation.

describe “#reader” do
it “returns word characters only” do
File.stub(:read).and_return(“hello, world”)
expect(reader.size).to eq(2)
expect(reader).to include(“hello”)
expect(reader).not_to include(’,’)
end
end

https://www.relishapp.com/rspec/rspec-mocks/v/3-0/docs/method-stubs/stub-with-a-simple-return-value

Can you explain line, File.stub(:read).and_return(“hello, world”) ?

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs