Skip to content

Instantly share code, notes, and snippets.

@foysavas
Forked from mattknox/inline_test
Created March 18, 2010 21:13
Show Gist options
  • Save foysavas/336903 to your computer and use it in GitHub Desktop.
Save foysavas/336903 to your computer and use it in GitHub Desktop.
> ruby -rmath_functions.rb -e "puts MathFunctions.factorial(2)"
2
> ruby --test -rmath_functions.rb
.
Finished in 1.000706 seconds.
1 tests, 2 assertions, 0 failures, 0 errors
module MathFunctions
def self.factorial(n)
(1..n).inject(1) { |acc, x| acc * x}
end
end
=begin :unittest
assert MathFunctions.factorial(6) == 720
assert MathFunctions.factorial(5) == 120
=end
@jeroenvandijk
Copy link

Hi Foy,

I just heard you mention inline testing in a podcast. I've been thinking about this as well and had a more complex solution. Yours looks interesting, but it doesn't work on my command line. Apparently the --test flag isn't know, what ruby version are you using? I'm assuming that this is not a fictive example, or is it?

Jeroen

@foysavas
Copy link
Author

foysavas commented May 3, 2010

Alas, you're right: this gist is total fiction, and we were really just starting to consider the potential syntax and semantics for inline unit tests.

My goals here were to:

  1. have something similar to D unit tests ( http://www.digitalmars.com/d/2.0/unittest.html )
  2. maintain backward compatibility at no cost when it came to interpreting the code

I'm starting to think however that this may be a bit short-sighted and that pushing for a 'conditional interpretation' keyword similar to D's 'version' ( http://www.digitalmars.com/d/2.0/version.html ) might be the right choice since it'd not only read better but serve wider purposes.

Out of interest, what was your complex solution?

@jeroenvandijk
Copy link

Very Interesting.

I was thinking about inline tests with the following goals in mind:

  • no need to worry anymore where to put your test, no need to switch to a separate file, just put it above the (method, class or module) definition
  • reuse the tests as example code

So I was thinking to add the test between the normal documentation for a method/module/class. I have currently focused on methods only.

The solution I have come up with is based on the Module#method_added hook method. I need to work it out further to give you a good example, but here is some code I extracted from the code I'm working on http://gist.github.com/388532#file_inline_test.feature . This doesn't work, but I hope it gives you an idea. I do have something simple (like the feature example) working locally.

What do you think of this approach?

@jeroenvandijk
Copy link

FYI, I have restructured stuff and started writing a simple gem and added some examples using rspec.

Not sure how this will end up. Here is the repo http://github.com/jeroenvandijk/inline_tests

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment