How to share data between implementation and description of a spec? - ruby

I wonder if there's any good way to reuse data between implementation and description of a spec... More particularly, I'd like to be able do something like the following:
describe "#some_method" do
let(:arg1) { "Sample String 1" }
let(:arg2) { "Sample String 2" }
context "with '#{arg1}', its result" do
specify { some_method(arg1).should == 1 }
end
context "with '#{arg2}', its result" do
specify { some_method(arg2).should == 2 }
end
end
Of course, this code won't work - arg1 and arg2 are not accessible outside of spec bodies.
Is it possible to achieve the similar result without using global variables or external classes?
Update:
I'm interested in the output of the spec. Something like this:
#some_method
with 'Sample String 1' its result
should == 1
with 'Sample String 2' its result
should == 2

The answer is that you don't use dynamic descriptions. The RSpec way to do this would be
describe "#some_method" do
it "extracts the number correctly" do
some_method("Sample String 1").should == 1
some_method("Sample String 2").should == 2
end
end
It is no problem to hard-code test data in your specs. If you want more complete output, you can use a custom matcher
require 'rspec'
class Test
def some_method(str)
str[/[0-9]+/].to_i
end
end
RSpec::Matchers.define :return_value_for_argument do |result, arg|
match do |actual|
actual.call(arg) == result
end
description do
"return #{result.inspect} for argument #{arg.inspect}"
end
end
describe Test do
let(:test) { Test.new }
describe "#some_method" do
subject { test.method(:some_method) }
it { should return_value_for_argument 1, "str 1" }
end
end

When doing API testing, I find it incredibly useful to be able to see the path, params, and response of each test. I have used the very useful tips given by Jeff Nyman to store things in the example.metatadata[:thing_i_want_to_store_like_url] of each test and with a custom formatter, print it out.
So my tests output look something like this:
that jonathan does not know it exists
:path : /user/20
:params: {}
=> response: {"error"=>{"message"=>"error", "code"=>404}}
that jonathan cannot edit
:path : /user/20/update
:params: {:name=>"evil_name"}
=> response: {"error"=>{"message"=>"error", "code"=>404}}

It's not appropriate to cite specific arguments in your descriptions. Your descriptions should provide a human-readable description of the desired behavior, without reference to specific arguments in most cases.

Related

RSpec navigatable it_behaves_like/shared_examples using LSP

I have a legacy project that uses shared_examples feature a lot and it is very inconvenient to navigate between actual specs and shared_examples implementation.
For now, the only way to do it is to search globally within a project using "some example" example name.
RSpec.shared_examples "some example" do |parameter|
let(:something) { parameter }
it "uses the given parameter" do
expect(something).to eq(parameter)
end
end
RSpec.describe SomeClass do
# "some example" has to become *something*
# I can click and navigate to(jump-to-definition)
include_examples "some example", "parameter1"
end
I would like to use LSP/Solargraph for this kind of navigation.
Perhaps anyone did this before and willing to share how they did it?
This turned out simpler than I expected.
Just extract your example name as a string constant and put it somewhere next to RSpec.shared_examples implementation.
# spec/support/shared_examples.rb
# in case you prefer one-liner use:
# RSpec.shared_examples(A_COLLECTION = 'a collection') do
# otherwise:
A_COLLECTION = 'a collection'
RSpec.shared_examples A_COLLECTION do
let(:collection) { described_class.new([7, 2, 4]) }
context 'initialized with 3 items' do
it 'says it has three items' do
expect(collection.size).to eq(3)
end
end
end
# spec/array_spec.rb
RSpec.describe Array do
it_behaves_like A_COLLECTION
end
HINT: In case it doesn't work for you, check .solargraph.yml config which excludes "spec/**/*" from indexing by default.

First attempt in Ruby Rspec

I am new to Ruby and Rspec, and so I happened to found this bit of code:
Here is my Specification:
RSpec.describe Surveyor::Answer, '03: Answer validations' do
context "for a free text question" do
let(:question) { double(Surveyor::Question, type: 'free_text') }
# NOTE: The rating validations should not apply for 'free_text' questions.
subject { described_class.new(question: question, value: 'anything') }
it { should be_valid }
end
Here is my Class:
module Surveyor
class Answer
def initialize(question_answer)
#question = question_answer[:question]
#answer = question_answer[:value]
end
def question_type
# I want to check what is the type of question here.
# 'free_text' or 'rating'
# if free_text
# print question type
# else
# do something
end
end
My question is how can I print(puts) the type of question (free_text/rating) in Answer class?
When I tried using print question_answer[:question]it only gave me #<Double Surveyor::Question>
So I could not use question_answer[:question][:type]
You can access the type in the constructor simply: question_answer[:question].type, or later in object level methods: #question.type.
You can't access it like question_answer[:question][:type] because the double method in the test creates a classic like object rather than a hash.
A tip: when a method accepts parameters as a single hash you can simply name that as options or params but if you have only 3-4 params, you can use separate variables for params instead of a hash

How do I convert from "should" to "expect" convention?

I've just started working with rspec, and I use expect instead of should convention.
How can I transform this test example from CanCan from should to expect?:
require "cancan/matchers"
# ...
describe "User" do
describe "abilities" do
subject { ability }
let(:ability){ Ability.new(user) }
let(:user){ nil }
context "when is an account manager" do
let(:user){ Factory(:accounts_manager) }
it{ should be_able_to(:manage, Account.new) }
end
end
end
You actually don't have to replace this instance of should, per Using implicit `subject` with `expect` in RSpec-2.11, but if you want to, you'd have to give up the one-liner approach and use:
it "should be able to manage a new account" do
expect(ability).to be_able_to(:manage, Account.new)
end
in place of the current it clause. As an aside, there looks to be some extraneous code in this test.

How can I test rspec user input and output with Highline?

I'd like to test response to user input. That input is queried using Highline:
def get_name
return HighLine.new.ask("What is your name?")
end
I'd like to do something similar to this question and put it in my test:
STDOUT.should_receive(:puts).with("What is your name?")
STDIN.should_receive(:read).and_return("Inigo Montoya")
MyClass.new.get_name.should == "Inigo Montoya"
What is the correct way to do this with Highline?
The best way to find out how to test Highline is to see how the author tests his package.
class TestHighLine < Test::Unit::TestCase
def setup
#input = StringIO.new
#output = StringIO.new
#terminal = HighLine.new(#input, #output)..
end
..
def test_agree
#input << "y\nyes\nYES\nHell no!\nNo\n"
#input.rewind
assert_equal(true, #terminal.agree("Yes or no? "))
assert_equal(true, #terminal.agree("Yes or no? "))
assert_equal(true, #terminal.agree("Yes or no? "))
assert_equal(false, #terminal.agree("Yes or no? "))
....
#input.truncate(#input.rewind)
#input << "yellow"
#input.rewind
assert_equal(true, #terminal.agree("Yes or no? ", :getc))
end
def test_ask
name = "James Edward Gray II"
#input << name << "\n"
#input.rewind
assert_equal(name, #terminal.ask("What is your name? "))
....
assert_raise(EOFError) { #terminal.ask("Any input left? ") }
end
Etc., as shown in his code. You can find this information in the highline source paying close attention to the setup, which I have highlighted in the link.
Notice how he uses the STDIN IO pipe to act in the place of typing the keys on the keyboard.
What this indicates, really, is that you don't need to use highline to test that kind of thing. The setup in his tests are really key here. Along with his use of StringIO as an object.
Highline already has it's own tests to make sure that it outputs to STDOUT and reads from STDIN. There is no reason to write these types of tests. It's the same reason that you would not write ActiveRecord tests that make sure attributes can be saved and read from the database.
However...
it would be extremely useful if there were a framework for Highline that works in a similar fashion as Capybara for web forms...
something that actually drives the input from the UI and tests the logic of your command-line utility.
For example, the following kind of hypothetical test would be nice:
run 'my_utility.rb'
highline.should :show_menu
select :add
highline.should(:ask).with_prompt("name?")
enter "John Doe"
output.should == "created new user"
I have published HighLine::Test - it allows you to run your tests in one process and your application in another (in the same way as you would with browser-based tests with Selenium).
GitHub link: https://github.com/joeyates/highline-test
gem: 'highline-test'
I worked on this DSL to try to solve this problem:
https://github.com/bonzofenix/cancun
require 'spec_helper'
describe Foo do
include Cancun::Highline
before { init_highline_test }
describe '#hello' do
it 'says hello correctly' do
execute do
Foo.new.salute
end.and_type 'bonzo'
expect(output).to include('Hi bonzo')
end

How to test stdin for a CLI using rspec

I'm making a small Ruby program and can't figure out how to write RSpec specs that simulate multiple user command line inputs (the functionality itself works). I think this StackOverflow answer probably covers ground that is closest to where I am, but it's not quite what I need. I am using Thor for the command line interface, but I don't think this is an issue with anything in Thor.
The program can read in commands either from a file or the command line, and I've been able to successfully write tests to read in an execute them. Here's some code:
cli.rb
class CLI < Thor
# ...
method_option :filename, aliases: ['-f'],
desc: "name of the file containing instructions",
banner: 'FILE'
desc "execute commands", "takes actions as per commands"
def execute
thing = Thing.new
instruction_set do |instructions|
instructions.each do |instruction|
command, args = parse_instruction(instruction) # private helper method
if valid_command?(command, args) # private helper method
response = thing.send(command, *args)
puts format(response) if response
end
end
end
end
# ...
no_tasks do
def instruction_set
if options[:filename]
yield File.readlines(options[:filename]).map { |a| a.chomp }
else
puts usage
print "> "
while line = gets
break if line =~ /EXIT/i
yield [line]
print "> "
end
end
end
# ..
end
I've tested successfully for executing commands contained in a file with this code:
spec/cli_spec.rb
describe CLI do
let(:cli) { CLI.new }
subject { cli }
describe "executing instructions from a file" do
let(:default_file) { "instructions.txt" }
let(:output) { capture(:stdout) { cli.execute } }
context "containing valid test data" do
valid_test_data.each do |data|
expected_output = data[:output]
it "should parse the file contents and output a result" do
cli.stub(:options) { { filename: default_file } } # Thor options hash
File.stub(:readlines).with(default_file) do
StringIO.new(data[:input]).map { |a| a.strip.chomp }
end
output.should == expected_output
end
end
end
end
# ...
end
and the valid_test_data referred to above is in the following form:
support/utilities.rb
def valid_test_data
[
{
input: "C1 ARGS\r
C2\r
C3\r
C4",
output: "OUTPUT\n"
}
# ...
]
end
What I want to do now is exactly the same thing but instead of reading each command from the 'file' and executing it, I want to somehow simulate a user typing in to stdin. The code below is utterly wrong, but I hope it can convey the direction I want to go.
spec/cli_spec.rb
# ...
# !!This code is wrong and doesn't work and needs rewriting!!
describe "executing instructions from the command line" do
let(:output) { capture(:stdout) { cli.execute } }
context "with valid commands" do
valid_test_data.each do |data|
let(:expected_output) { data[:output] }
let(:commands) { StringIO.new(data[:input]).map { |a| a.strip } }
it "should process the commands and output the results" do
commands.each do |command|
cli.stub!(:gets) { command }
if command == :report
STDOUT.should_receive(:puts).with(expected_output)
else
STDOUT.should_receive(:puts).with("> ")
end
end
output.should include(expected_output)
end
end
end
end
I've tried using cli.stub(:puts) in various places, and generally rearranging this code around a lot, but can't seem to get any of my stubs to put data in stdin. I don't know if I can parse the set of inputs I expect from the command line in the same way as I do with a file of commands, or what code structure I should be using to solve this issue. If someone who has spec-ed up command-line apps could chime in, that would be great. Thanks.
Rather than stubbing the universe, I think a few bits of indirection would help you write a unit test for this code. The simplest thing you can do is to allow the IO object for output to be injected, and default it to STDOUT:
class CLI < Thor
def initialize(stdout=STDOUT)
#stdout = stdout
end
# ...
#stdout.puts # instead of raw puts
end
Then, in your tests, you can use a StringIO to examine what was printed:
let(:stdout) { StringIO.new }
let(:cli) { CLI.new(stdout) }
Another option is to use Aruba or something like it, and write full-on integration tests, where you actually run your program. This has other challenges as well (such as being nondestructive and making sure not to squash/use system or user files), but will be a better test of your app.
Aruba is Cucumber, but the assertions can use RSPec matchers. Or, you can use Aruba's Ruby API (which is undocumented, but public and works great) to do this without the hassle of Gherkin.
Either way, you will benefit from making your code a bit more test-friendly.
I ended up finding a solution that I think fairly closely mirrors the code for executing instructions from a file. I overcame the main hurdle by finally realizing that I could write cli.stub(:gets).and_return and pass it in the array of commands I wanted to execute (as parameters thanks to the splat * operator), and then pass it the "EXIT" command to finish. So simple, yet so elusive. Many thanks go to this StackOverflow question and answer for pushing me over the line.
Here is the code:
describe "executing instructions from the command line" do
let(:output) { capture(:stdout) { cli.execute } }
context "with valid commands" do
valid_test_data.each do |data|
let(:expected_output) { data[:output] }
let(:commands) { StringIO.new(data[:input]).map { |a| a.strip } }
it "should process the commands and output the results" do
cli.stub(:gets).and_return(*commands, "EXIT")
output.should include(expected_output)
end
end
end
# ...
end
Have you looked at Aruba? It lets you write Cucumber feature tests for command line programs. You can define the input to your CLI that way.
You can write you feature definitions with RSpec, so it's not completely new.
You can stub all Thor::Actions with Rspec's allow_any_instance_of
here is one example:
it "should import list" do
allow_any_instance_of(Thor::Actions).to receive(:yes?).and_return(true)
end

Resources