百科.dev
全部条目在线工具AI 编程趋势榜开源项目技术资讯提交条目
登录
< 返回工具列表
P

pretentious

> 编程语言
开源

用于编写特性测试的工具 - 以直观的方式根据现有行为生成 RSpec 或 minitest 规范

99 stars0 点赞1 次浏览
访问官网GitHub

工具介绍

用于编写特性测试的工具 - 以直观的方式根据现有行为生成 RSpec 或 minitest 规范

Ruby::Pretentious

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.

Table of Contents

  1. Installation
  2. Usage
  3. Using the pretentious.yml file
  4. Declarative generation without using example files
  5. Minitest
  6. Handling complex parameters and object constructors
  7. Capturing Exceptions
  8. Auto Stubbing
  9. Object Deconstruction Utility
  10. Using the Object deconstructor in rails
  11. Things to do after
  12. Limitations

Installation

Add this line to your application's Gemfile:

ruby
gem 'pretentious'

And then execute:

$ bundle

Or install it yourself as:

$ gem install pretentious

Usage

The 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.

Using an example file

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:

ruby
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

Inside 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:

ruby
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
end

Save your file and then switch to the terminal to invoke:

$ pretentious example.rb

This 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:

ruby
#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
end

The 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 ...

ruby
#example.rb

Pretentious.spec_for(Digest::MD5) do
  sample = "This is the digest"
  Digest::MD5.hexdigest(sample)
end

You should get something like:

ruby
# 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
end

Note: 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.

Commandline options

If you already have an example file you can also use various command line options.

passing --help will show these options

ruby
pretentious --help

The command below will generate tests for Meme using the provided example file.

ruby
pretentious -t Meme sample.rb
pretentious -t $/Meme/ sample.rb # generate tests for all classes starting with Meme

Note: class methods are not captured using this method

Using pretentious.yml

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:

yaml
# 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.rb

It 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.

Declarative generation without using example files

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:

ruby
# 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 root

The 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

ruby
# 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 root

or, use the FileWriter utility to write it to a file

ruby
# 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
end

IMPORTANT: 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:

ruby
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:

ruby
Pretentious.on(UsersController).method_called(:login).spec_for(/^User/)

Classes starting with User will now be watched (e.g. UserController, UserProfile etc.)

Minitest

The minitest test framework is also supported, simply use Pretentious.minitest_for instead

ruby
Pretentious.minitest_for(Meme) do
  meme = Meme.new
  meme.i_can_has_cheezburger?
  meme.will_it_blend?
end

outputs:

ruby
# This file was automatically generated by the pretentious gem
require 'minitest_helper'
require 'minitest/autorun'

class MemeTest e
  end

should generate the following in rspec

ruby
  # TestClass1#something_is_wrong when passed  should return StandardError
  expect { @fixture.something_is_wrong }.to raise_error

Auto stubbing

Too 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):

ruby
Pretentious.spec_for(TestClass._stub(ClassUsedByTestClass)) do
  instance = TestClass.new
  instance.method_that_uses_the_class_to_stub
end

should auto generate the stub like this:

ruby
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!!!!"])

end

For minitest it returns something like:

ruby
class Scenario2 1, :str=>"hello world", :message=>"a message"}
      assert_equal var_2174209040, @fixture.method_with_usage3("a message")

    end

  end
end

Note: 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):

ruby
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:

ruby
Pretentious.spec_for(TestClass._stub(ClassUsedByTestClass, AnotherClassUsedByTestClass, ....)) do
  instance = TestClass.new
  instance.method_that_uses_the_class_to_stub
end

Note: different return values are only supported on RSpec for now

Object Deconstruction Utility

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· 0 开放

查看全部 Issues在 GitHub 打开

暂无开放 Issues,或尚未同步最近议题。

> 标签

Ruby

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月18日
分类编程语言
定价开源

> 相关工具

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言