用于编写特性测试的工具 - 以直观的方式根据现有行为生成 RSpec 或 minitest 规范
Do you have a pretentious boss or development lead that pushes you to embrace BDD/TDD but for reasons hate it or them? here is a gem to deal with that. Now you CAN write your code first and then GENERATE tests later!! Yes you heard that right! To repeat, this gem allows you to write your code first and then automatically generate tests using the code you've written in a straightfoward manner!
On a serious note, this gem allows you to generate tests template used for "characterization tests" much better than those generated by default for various frameworks. It is also useful for "recording" current behavior of existing components in order to prepare for refactoring. As a bonus it also exposes an Object Deconstructor which allows you, given any object, to obtain a ruby code on how it was created.
Add this line to your application's Gemfile:
gem 'pretentious'And then execute:
$ bundleOr install it yourself as:
$ gem install pretentiousThe are various ways to use the pretentious gem. First is using an example file. An example file is simply a ruby script that uses your target class in a way that you want to test. The pretentious gem will then analyze what methods are called, how it is created and generate test cases for it.
The other way is using an init file to declare which classes to test and when. This is useful if you want to document how a class is used in an existing application. This is the prefered method for characterization testing on framework like rails.
There are also various commandline options available.
Please refer to the table of contents to skip directly to the specific use case.
First Create an example file (etc. example.rb) and define the classes that you want to test, if the class is already defined elsewhere just require them. Below is an example:
class Fibonacci
def fib(n)
return 0 if (n == 0)
return 1 if (n == 1)
return 1 if (n == 2)
return fib(n - 1) + fib(n - 2)
end
def self.say_hello
"hello"
end
endInside a Pretentious.spec_for(...) block. Just write boring code that instantiates an object as well as calls the methods like how you'd normally use them. Finally Specify the classes that you want to test:
class Fibonacci
def fib(n)
return 0 if (n == 0)
return 1 if (n == 1)
return 1 if (n == 2)
return fib(n - 1) + fib(n - 2)
end
def self.say_hello
"hello"
end
end
Pretentious.spec_for(Fibonacci) do
instance = Fibonacci.new
(1..10).each do |n|
instance.fib(n)
end
Fibonacci.say_hello
endSave your file and then switch to the terminal to invoke:
$ pretentious example.rbThis will automatically generate rspec tests for Fibonacci under /spec of the current working directory.
You can actually invoke rspec at this point, but the tests will fail. Before you do that you should edit spec/spec_helper.rb and put the necessary requires and definitions there.
For this example place the following into spec_helper.rb:
#inside spec_helper.rb
class Fibonacci
def fib(n)
return 0 if (n == 0)
return 1 if (n == 1)
return 1 if (n == 2)
return fib(n - 1) + fib(n - 2)
end
def self.say_hello
"hello"
end
endThe generated spec file should look something like this
…awesome! Note that this approach is the only way to capture calls to class methods.
You can also try this out with libraries like MD5 for example ...
#example.rb
Pretentious.spec_for(Digest::MD5) do
sample = "This is the digest"
Digest::MD5.hexdigest(sample)
endYou should get something like:
# This file was automatically generated by the pretentious gem
require 'spec_helper'
RSpec.describe Digest::MD5 do
it 'should pass current expectations' do
sample = 'This is the digest'
# Digest::MD5::hexdigest when passed "This is the digest" should return '9f12248dcddeda976611d192efaaf72a'
expect(Digest::MD5.hexdigest(sample)).to eq('9f12248dcddeda976611d192efaaf72a')
end
endNote: If your test subject is already part of a larger application and would like to capture behavior in the manner that the application uses it, please look at Declarative Generation.
If you already have an example file you can also use various command line options.
passing --help will show these options
pretentious --helpThe command below will generate tests for Meme using the provided example file.
pretentious -t Meme sample.rb
pretentious -t $/Meme/ sample.rb # generate tests for all classes starting with MemeNote: class methods are not captured using this method
If you run pretentious without passing an example file, it will look for pretentious.yml in the current location. Below is an example pretentious.yml file:
# Sample pretentious targets file
# use $ to pass a regex or a ruby code that evals to a string
targets:
- class: Meme
- class: $/^TestClass/
generators:
- rspec
- minitest
examples:
- sample.rbIt basically contains three parts, the target classes to generate test for, the generators to use (rspec/minitest) and the example files to run. Note that in this case, Pretentious.spec_for/minitest_for is not needed in the example file as the target classes are already specified in the targets section.
Instead of using Pretentious.spec_for and wrapping the target code around a block, you may declaratively define when test generation should occur beforehand. This allows you to generate tests around code blocks without modifying source codes. This is useful for testing code embedded inside frameworks like rails where your "example" is already embedded inside existing code.
For example lets say you want to generate tests for UserAuthenticaion that is used inside the login method inside the UsersController inside a Rails app. You'd simply define like below:
# initializers/pretentious.rb
Pretentious.install_watcher # install watcher if not defined previously
if Rails.env.test? #IMPORTANT don't run this when you don't need it!
Pretentious.on(UsersController).method_called(:login).spec_for(UserAuthentication) #RSPEC
Pretentious.on(UsersController).method_called(:login, :logout, ...).minitest_for(UserAuthentication) #minitest
end
# spec files will be written to the project rootThe above code is equivalent to adding a spec_for inside the target method.
Note that you must include the setup code in a place that you know runs before the target code block is run. For example, if you want to test a class that is used inside a controller in rails, it is best to put it in an initializer. It is also recommended to call Pretentious.install_watcher early on to be able to generate better fixtures.
You can pass a block for manually handling the output, for example
# initializers/pretentious.rb
Pretentious.install_watcher # install watcher if not defined previously
if Rails.env.test? #IMPORTANT don't run this when you don't need it!
Pretentious.on(UsersController).method_called(:login).spec_for(UserAuthentication) do |results|
puts results[UserAuthentication][:output]
end
end
# spec files will be written to the project rootor, use the FileWriter utility to write it to a file
# initializers/pretentious.rb
Pretentious.install_watcher # install watcher if not defined previously
if Rails.env.test? #IMPORTANT don't run this when you don't need it!
Pretentious.on(UsersController).method_called(:login).spec_for(UserAuthentication) do |results|
file_writer = Pretentious::FileWriter.new
file_writer.write UserAuthenticaion, results[UserAuthenticaion]
end
endIMPORTANT: If using rails or if it is part of a larger app, make sure to enable this only when you intend to generate specs! delete the initializer or comment the code out when it is not needed.
If the class is still to be defined, you may pass the name of the class as a string instead. However, calls to class methods can't be reliably captured in this manner:
Pretentious.on(UsersController).method_called(:login).spec_for("UserAuthentication")Of course, you call also pass a regex if you want to auto generate classes via some name convention:
Pretentious.on(UsersController).method_called(:login).spec_for(/^User/)Classes starting with User will now be watched (e.g. UserController, UserProfile etc.)
The minitest test framework is also supported, simply use Pretentious.minitest_for instead
Pretentious.minitest_for(Meme) do
meme = Meme.new
meme.i_can_has_cheezburger?
meme.will_it_blend?
endoutputs:
# This file was automatically generated by the pretentious gem
require 'minitest_helper'
require 'minitest/autorun'
class MemeTest e
endshould generate the following in rspec
# TestClass1#something_is_wrong when passed should return StandardError
expect { @fixture.something_is_wrong }.to raise_errorToo lazy to generate rspec-mocks stubs? Let the Pretentious gem do it for you.
Simply call the _stub method on a class and pass the classes you want to generate stubs for when passing calling spec_for or minitest_for (see below):
Pretentious.spec_for(TestClass._stub(ClassUsedByTestClass)) do
instance = TestClass.new
instance.method_that_uses_the_class_to_stub
endshould auto generate the stub like this:
it 'should pass current expectations' do
var_2181613400 = ["Hello Glorious world", "HI THERE!!!!"]
allow_any_instance_of(ClassUsedByTestClass).to receive(:a_stubbed_method).and_return("Hello Glorious world")
# TestClass#method_that_uses_the_class_to_stub should return ["Hello Glorious world", "HI THERE!!!!"]
expect( @fixture.method_that_uses_the_class_to_stub ).to eq(["Hello Glorious world", "HI THERE!!!!"])
endFor minitest it returns something like:
class Scenario2 1, :str=>"hello world", :message=>"a message"}
assert_equal var_2174209040, @fixture.method_with_usage3("a message")
end
end
endNote: Stubbing on minitest requires the minitest-stub_any_instance gem.
stubs that return different values every call are automatically detected an the appropriate rspec stub return is generated (similar to below):
allow_any_instance_of(TestMockSubClass).to receive(:increment_val).and_return(2, 3, 4, 5)Yes, you can pass in multiple classes to be stubbed:
Pretentious.spec_for(TestClass._stub(ClassUsedByTestClass, AnotherClassUsedByTestClass, ....)) do
instance = TestClass.new
instance.method_that_uses_the_class_to_stub
endNote: different return values are only supported on RSpec for now
As Pretentious as the gem is, there are other uses other than generating tests specs. Tools are also available to deconstruct objects. Object deconstruction basically means that the components used to create and initialize an object are extr
暂无开放 Issues,或尚未同步最近议题。