Spec example description

I am looking at the source code of crystal/src/spec/example.cr and I would love to have access to the Example’s description field from my specs.

People may be asking why would you want to do that ? The reason is that I have a lot of golang specs in the form of

t = {text: "thing to be tested", error: "some error", result: false}

I am editing those tests to get them in the following form (it is a lot of work)

it "thing to be tested" do
 test_example = `insert the description as a variable like Spec::Example.get_description()`
 ... do test with test_example ...
end

Thanks for reading and/or helping

1 Like

Sorry, I don’t follow what you need the description for. Can you show an actual example of what you want to do?

1 Like

Let say I want to test some math operation

it "1 + 2" do
  expr = "1 + 2"
  mytest(expr)
end

I would like to do this

it "1 + 2" do
  expr = get_description_of_this_spec()
  # expr should no hold "1 + 2"
  mytest(expr)
end

Maybe the spec runner could yield the instance of Spec::Example to the block. This might even have been proposed before, I’m not sure. But it currently doesn’t work.

A simple workaround would be to use a helper method to build the example:

def it_exp(description, file = __FILE__, line = __LINE__, &block)
  it description, file: file, line: line do
    block.call(description)
  end
end

it_exp "1 + 2" do |expr|
  mytest(expr)
end
1 Like

But what do you want to do with the description? In your example you pass it to a method, but what does the method do? We need to know the exact use case. For example if you need the description to show it when the spec fails, that’s already being done by the spec runner. Then, there’s no eval in Crystal so you can’t really work with that expression.

So what do you need the Example instance for?

That said, I wouldn’t mind adding it as a block argument, but please provide a real use case.

Thanks, great, exactly what I need.

I guess a use case would be some kind of parser or anything that somehow handles a string. Then it would make sense to use the same string for both the description of the spec as well as the sample being tested.

This use case is present in the compiler specs. it_parses from parser_spec.cr is pretty similar to my workaround. But as with it_parses, I suppose that most use cases would warrant a custom helper method anyway which also provides additional setup and even the matcher itself (it_parses doesn’t receive a block).

I need this. I need to use Spec::Item.description for the name of each test’s snapshot file. Otherwise each test will have 2 copies of the description text.

bad:

  it "lists some JSON for user" do
    res = process_request req
    res.body.should match_snapshot "Http/Posts/List/lists some JSON for user"
  end

good:

  it "lists some JSON for user" do
    res = process_request req
    res.body.should match_snapshot "Http/Posts/List/#{self.description}"
  end