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

riot

> 编程语言
开源

Riot 是一个快速、表达力强且具上下文性的 Ruby 单元测试框架

315 stars0 点赞5 次浏览
访问官网GitHub

工具介绍

Riot 是一个快速、表达力强且具上下文性的 Ruby 单元测试框架

Riot

A fast, expressive, and contextual ruby unit testing framework. Protest the slow test.

Installation

gem install riot

Usage

In contrast to other popular Ruby testing frameworks such as Test::Unit, Shoulda and RSpec, Riot does not run a setup and teardown sequence before and after each test. This speeds up test execution quite a bit, but also changes how you write your tests. In general and in my opinion, you should avoid mutating any objects under test and if you use Riot you're pretty much going to have to.

In Riot, tests reside in contexts. Within these, a topic object is defined through a setup block. The actual assertions are then made with an asserts or denies block.

ruby
context "An empty Array" do
  setup { Array.new }
  asserts("it is empty") { topic.empty? }
  denies("it has any elements") { topic.any? }
end # An Array

As you can see, the setup block doesn't use any instance variables to save the object under test — rather, the return value of the block is used as the topic. This object can then be accessed in the assertions using the topic attribute. Furthermore, at their very basic level, assertions need only return a boolean. When using asserts, true indicates a pass while false indicates a fail; subsequently, when using denies, true indicates a failure whereas false indicates success.

Of course, you can nest contexts as well; the setup blocks are executed outside-in; as in, the parents' setups are run before the current context allowing for a setup hierarchy. teardown blocks are run inside out; the current context's teardowns are run before any of its parents'. This is what you would expect from other frameworks as well.

ruby
context "An Array" do
  setup { Array.new }

  asserts("is empty") { topic.empty? }

  context "with one element" do
    setup { topic  "[email protected]") }.assigns(:email, "[email protected]")
denies("a person") { Person.new(:email => "[email protected]") }.assigns(:email, "[email protected]")
asserts.assigns { :email }
denies.assigns { :email }
asserts.assigns(:email) { "[email protected]" }
denies.assigns(:email) { "[email protected]" }

Nil

Simply checks the actual value for its nil-ness. Expects no arguments.

ruby
asserts.nil
denies.nil

Matches

Compares the actual value to a provided regular expression

ruby
asserts.matches(%r{Regex})
denies.matches(%r{Regex})
asserts.matches { /Regex/ }
denies.matches { /Regex/ }

Raises

Validates the type of exception raised from the assertion block. Optionally, you can give it the message you expected in the form of a literal string or even a portion of it.

ruby
asserts.raises(ExceptionClass)
denies.raises(ExceptionClass)
asserts.raises(ExceptionClass, "Expected message")
denies.raises(ExceptionClass, "Expected message")
asserts.raises(ExceptionClass) { "ted mess" }
denies.raises(ExceptionClass) { "ted mess" }

Kind Of

Validates the type of object returned from the assertion block

ruby
asserts.kind_of(Class)
denies.kind_of(Class)
asserts.kind_of { Class }
denies.kind_of { Class }

Responds To

Checks that the actual object respond_to? to a particular message

ruby
asserts.respond_to(:foo)
denies.respond_to(:foo)
asserts.respond_to { "foo" }
denies.respond_to { "foo" }
asserts.responds_to("foo")
denies.responds_to("foo")
asserts.responds_to { :foo }
denies.responds_to { :foo }

Includes

Checks for the existence of: a character or sequence of characters in a string, an element in an array, or a key in a hash.

ruby
asserts("this string") { "barbie q" }.includes("foo")
denies("this string") { "barbie q" }.includes("foo")
asserts("this array") { [1,2,3] }.includes(2)
denies("this array") { [1,2,3] }.includes(2)
asserts("this hash") { {:key1 => "foo"} }.includes(:key2)
denies("this hash") { {:key1 => "foo"} }.includes(:key2)
asserts.includes { "foo" }
denies.includes { "foo" }
asserts.includes { 2 }
denies.includes { 2 }
asserts.includes { :key }
denies.includes { :key }

Size

Compares the size of the actual object to the number you provide. Works with anything that responds to size(Numeric) (strings, arrays, hashes, etc).

ruby
asserts.size(Numeric)
denies.size(Numeric)
asserts.size { Numeric }
denies.size { Numeric }

Empty

Checks the result of calling empty? on the actual value. Expects no arguments.

ruby
asserts.empty
denies.empty

Same Elements

Compares actual to expected to see if they contain the same elements. Uses Set under-the-hood, just so you know.

ruby
asserts.same_elements(Array)
denies.same_elements(Array)
asserts.same_elements { Array }
denies.same_elements { Array }

Setups, Hookups, and Helpers

We're not even close to done yet; there's a lot more cool stuff for you to know about. You know about setup already; but you may not know that you can call setup multiple times within a Context. Well, you can. They run in the order you write them (top-down) and the result of a prior setup will be the topic for the next setup. In this way you could chain together some partitioned setup criteria without ever explicitly setting a variable (instance or local).

ruby
context "A cheesey order" do
  setup { Cheese.create!(:name => "Blue") }
  setup { Order.create!(:cheese => topic, :purchase_order => "123-abc") }

  asserts_topic.kind_of(Order) # I love tests that are readable
end # A cheesey order

This notion about a prior setup being the topic for a latter setup is true even when the setup is called from a parent Context.

More than likely, however, you'll want to modify something about the topic without changing what the topic for the context is. To do this, Riot provides the hookup block, which is just like a setup block except that hookup will always return the topic that was provided to it. It's kind of like calling Object#tap. Here's a for-instance:

ruby
context "A Person" do
  setup { Person.new(:name => "Master Blasterr") }

  denies(:valid?) # :(

  context "with valid email" do
    hookup { topic.email = "[email protected]" }
    asserts(:valid?) # Yay!
  end # with valid email
end # A complex thing

If the point didn't smack you in the face there, think about using setup instead of hookup in the sub-context. Had you written that as a setup block, you'd have to return topic after setting the email address, or else the new topic would be the actual email address; and you probably don't want to actually be calling "[email protected]".valid? in the assertion.

You can also call hookup as many times as you like; the great part is that the topic never changes.

Helpers

You remember how you used to — or currently do — create instance variables to hold some data that you're going to use in your tests? Well, Riot allows you to still do that yucky stuff, but would rather you use a helper to encapsulate it. For instance, you could do this:

ruby
context "A greedy monkey" do
  setup do
    @a_ripe_banana = Banana.new(:ripe => true)
    Monkey.new
  end

  hookup { topic.takes(@a_ripe_banana) }

  asserts(:bananas).size(1)
end # A greedy monkey

Or, you could do this

ruby
context "A greedy monkey" do
  helper(:a_ripe_banana) { Banana.new(:ripe => true) }
  setup { Monkey.new }

  hookup { topic.takes(a_ripe_banana) }

  asserts(:bananas).size(1)
end # A greedy monkey

"So! What's the difference?", you ask. Nothing really. It's all aesthetic; but, it's a better aesthetic for a couple of reasons. Let me tell you why:

  1. Helpers are good ways to encapsulate related setup data and give that data namespace
  2. The act of setting up data does not clutter up your setups or assertions
  3. I'll argue that it makes the code more readable; ex. how do you verbalize to your friends @a_banana and a_banana. In the former, I probably say "at a banana" and think "Why do I sound like a muppet when I talk?".
  4. Being that helpers are blocks, you can actually pass arguments to them

What's that about (4)? Yes, helpers are really just over-glorified methods, which means you can pass arguments to them. Which means you can build factories with them. Which means those factories can go away when the context is no longer used and they're no longer cluttering up your object space. You want another for instance, eh?

ruby
context "A greedy monkey" do
  helper(:make_a_banana) do |color|
    Banana.new(:color => color)
  end

  setup { Monkey.new }

  hookup do
    topic.takes(make_a_banana("green"))
    topic.takes(make_a_banana("blue"))
  end

  asserts(:bananas).size(2)
  asserts("green bananas") { topic.bananas.green }.size(1)
  asserts("blue bananas") { topic.bananas.blue }.size(1)
end # A greedy monkey

Or you could make_many_bananas or whatever. There are also lots of clever ways to get helpers included into a context which you will hopefully see when you read up on Context Middleware and look through the Recipes. Riot Rails makes liberal use of helpers when setting up a context to test controllers.

Again, you define as many helpers as you like; you can also replace existing helpers by simply defining a helper with the same name (that's because they're just methods defined within the context instance ... shhh).

Running Riot

Running your Riot tests is pretty simple. You can put your test files wherever you want, but it's generally a good idea to put them in a "test" directory. You can run individual test files using the normal ruby command:

plain
ruby test/units/monkey_test.rb
# or
ruby -Itest test/units/monkey_test.rb

I like the latter and use it often. It means the test directory is loaded into the load path, which means I don't have to be explicit about where to find my teststrap.rb file (which you might have named test_helper.rb in other projects even though it's a silly name). In your teststrap file you'll put all your common setup; maybe even including your Riot hacks. An out-of-the-box teststrap might look like this:

ruby
require 'rubygems'
require ''
require 'riot'

Of course, you probably want to use rake to run your tests. Here's a basic Rakefile that will find our tests in the test directory or its subdirectories if the filename ends in _test.rb:

ruby
require 'rubygems'

require 'rake'
require 'rake/testtask'

desc "Run all our tests"
task :test do
  Rake::TestTask.new do |t|
    t.libs  :test

And then on the command line you simply run:

plain
rake
# or
rake test

Mocking

Mocking seems to be all the rage this decade. I try very hard to avoid it altogether through judicious use of anonymous classes, but sometimes you just need to mock. For Riot, RR seemed to fit the bill nicely because it's:

  • Lightweight
  • Laid back
  • Test framework agnostic and easy to integrate with
  • Starts and ends with TWO R's!

That second to last point needs to be stressed a bit more. RR's default behavior is to not give a crap about what test framework you use. I can already hear you thinking, "But wait, aren't you tying Riot to a mock framework?"

Well, not really. Riot is mock framework agnostic; it'll work with any framework that can be worked with. Riot does not implicitly require in any RR support; you have to do that in your test-strapping.

However, there are a number of things you expect from a test framework when mocking is involved. Namely, if a mock expectation fails you want the context or assertion to fail, too. Additionally, you don't want to have to ask the mocking framework to validate itself for each assertion; you want Riot to do that for you. And some other things. So, Riot does most of the tedious mock-lifting for you and it suggests you use RR, but doesn't require it.

But enough of this hemming and hawing. What's

Issues· 9 开放

查看全部 Issues在 GitHub 打开

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

> 标签

Ruby

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

> 工具信息

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

> 相关工具

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