File: getting-started.md

package info (click to toggle)
ruby-sus 0.35.2-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 380 kB
  • sloc: ruby: 2,844; makefile: 4
file content (401 lines) | stat: -rw-r--r-- 8,498 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
# Getting Started

This guide explains how to use the `sus` gem to write tests for your Ruby projects.

## Installation

Add the gem to your project:

~~~ bash
$ bundle add sus
~~~

## Write Some Tests

Create a test file in your project `test/my_project/my_class.rb`:

~~~ ruby
describe MyProject::MyClass do
	let(:instance) {subject.new}
	
	it "instantiates an object" do
		expect(instance).to be_a(Object)
	end
end
~~~

## Run Your Tests

Run your tests with the `sus` command:

~~~ bash
$ sus
1 passed out of 1 total (1 assertions)
๐Ÿ Finished in 47.0ยตs; 21272.535 assertions per second.
๐Ÿ‡ No slow tests found! Well done!
~~~

You can also run your tests in parallel:

~~~ bash
$ sus-parallel
~~~

## More Examples

Check out all the repositories in this organisation, including these notable examples:

- [sus/test](https://github.com/socketry/sus/tree/main/test/sus)
- [async/test](https://github.com/socketry/async/tree/main/test)

## Project Structure

Here is an example structure for testing with Sus - the actual structure may vary based on your gem's organization, but aside from the `lib/` directory, sus expects the following structure:

```
my-gem/
โ”œโ”€โ”€ config/
โ”‚   โ””โ”€โ”€ sus.rb                     # Sus configuration file
โ”œโ”€โ”€ lib/
โ”‚   โ”œโ”€โ”€ my_gem.rb
โ”‚   โ””โ”€โ”€ my_gem/
โ”‚       โ””โ”€โ”€ my_thing.rb
โ”œโ”€โ”€ fixtures/
โ”‚   โ””โ”€โ”€ my_gem/
โ”‚       โ””โ”€โ”€ a_thing.rb               # Provides MyGem::AThing shared context
โ””โ”€โ”€ test/
    โ”œโ”€โ”€ my_gem.rb                    # Tests MyGem
    โ””โ”€โ”€ my_gem/
        โ””โ”€โ”€ my_thing.rb              # Tests MyGem::MyThing
```

### Configuration File

Create `config/sus.rb`:

```ruby
# frozen_string_literal: true

# Use the covered gem for test coverage reporting:
require "covered/sus"
include Covered::Sus

def before_tests(assertions, output: self.output)
	# Starts the clock and sets up the test environment:
	super
end

def after_tests(assertions, output: self.output)
	# Stops the clock and prints the test results:
	super
end
```

### Fixtures Files

`fixtures/` gets added to the `$LOAD_PATH` automatically, so you can require files from there without needing to specify the full path.

### Test Files

Sus runs all Ruby files in the `test/` directory by default. But you can also create tests in any file, and run them with the `sus my_tests.rb` command.

## Test Syntax

### `describe` - Test Groups

Use `describe` to group related tests:

```ruby
describe MyThing do
	# The subject will be whatever is described:
	let(:my_thing) {subject.new}
end
```

### `it` - Individual Tests

Use `it` to define individual test cases:

```ruby
it "returns the expected value" do
	expect(result).to be == "expected"
end
```

You can use `it` blocks at the top level or within `describe` or `with` blocks.

### `with` - Context Blocks

Use `with` to create context-specific test groups:

```ruby
with "valid input" do
	let(:input) {"valid input"}
	it "succeeds" do
		expect{my_thing.process(input)}.not.to raise_exception
	end
end

# Non-lazy state can be provided as keyword arguments:
with "invalid input", input: nil do
	it "raises an error" do
		expect{my_thing.process(input)}.to raise_exception(ArgumentError)
	end
end
```

When testing methods, use `with` to specify the method being tested:

```ruby
with "#my_method" do
	it "returns a value" do
		expect(my_thing.my_method).to be == 42
	end
end

with ".my_class_method" do
	it "returns a value" do
		expect(MyThing.class_method).to be == "class value"
	end
end
```

### `let` - Lazy Variables

Use `let` to define variables that are evaluated when first accessed:

```ruby
let(:helper) {subject.new}
let(:test_data) {"test value"}

it "uses the helper" do
	expect(helper.process(test_data)).to be_truthy
end
```

### `before` and `after` - Setup/Teardown

Use `before` and `after` for setup and teardown logic:

```ruby
before do
	# Setup logic.
end

after do
	# Cleanup logic.
end
```

Error handling in `after` allows you to perform cleanup even if the test fails with an exception (not a test failure).

```ruby
after do |error = nil|
	if error
		# The state of the test is unknown, so you may want to forcefully kill processes or clean up resources.
		Process.kill(:KILL, @child_pid)
	else
		# Normal cleanup logic.
		Process.kill(:TERM, @child_pid)
	end
	
	Process.waitpid(@child_pid)
end
```

### `around` - Setup/Teardown

Use `around` for setup and teardown logic:

```ruby
around do |&block|
	# Setup logic.
	super() do
		# Run the test.
		block.call
	end
ensure
	# Cleanup logic.
end
```

Invoking `super()` calls any parent `around` block, allowing you to chain setup and teardown logic.

## Assertions

### Basic Assertions

```ruby
expect(value).to be == expected
expect(value).to be >= 10
expect(value).to be <= 100
expect(value).to be > 0
expect(value).to be < 1000
expect(value).to be_truthy
expect(value).to be_falsey
expect(value).to be_nil
expect(value).to be_equal(another_value)
expect(value).to be_a(Class)
```

### Strings

```ruby
expect(string).to be(:start_with?, "prefix")
expect(string).to be(:end_with?, "suffix")
expect(string).to be(:match?, /pattern/)
expect(string).to be(:include?, "substring")
```

### Ranges and Tolerance

```ruby
expect(value).to be_within(0.1).of(5.0)
expect(value).to be_within(5).percent_of(100)
```

### Method Calls

To call methods on the expected object:

```ruby
expect(array).to be(:include?, "value")
expect(string).to be(:start_with?, "prefix")
expect(object).to be(:respond_to?, :method_name)
```

### Collection Assertions

```ruby
expect(array).to have_attributes(length: be == 1)
expect(array).to have_value(be > 1)

expect(hash).to have_keys(:key1, "key2")
expect(hash).to have_keys(key1: be == 1, "key2" => be == 2)
```

### Attribute Testing

```ruby
expect(user).to have_attributes(
	name: be == "John",
	age: be >= 18,
	email: be(:include?, "@")
)
```

### Exception Assertions

```ruby
expect do
	risky_operation
end.to raise_exception(RuntimeError, message: be =~ /expected error message/)
```

## Combining Predicates

Predicates can be nested.

```ruby
expect(user).to have_attributes(
	name: have_attributes(
		first: be == "John",
		last: be == "Doe"
	),
	comments: have_value(be =~ /test comment/),
	created_at: be_within(1.minute).of(Time.now)
)
```

### Logical Combinations

```ruby
expect(value).to (be > 10).and(be < 20)
expect(value).to be_a(String).or(be_a(Symbol), be_a(Integer))
```

### Custom Predicates

You can create custom predicates for more complex assertions:

```ruby
def be_small_prime
	(be == 2).or(be == 3, be == 5, be == 7)
end
```

## Block Expectations

### Testing Blocks

```ruby
expect{operation}.to raise_exception(Error)
expect{operation}.to have_duration(be < 1.0)
```

### Performance Testing

You should generally avoid testing performance in unit tests, as it will be highly unstable and dependent on the environment. However, if you need to test performance, you can use:

```ruby
expect{slow_operation}.to have_duration(be < 2.0)
expect{fast_operation}.to have_duration(be < 0.1)
```

- For less unstable performance tests, you can use the `sus-fixtures-time` gem which tries to compensate for the environment by measuring execution time.

- For benchmarking, you can use the `sus-fixtures-benchmark` gem which measures a block of code multiple times and reports the execution time.

## File Operations

### Temporary Directories

Use `Dir.mktmpdir` for isolated test environments:

```ruby
around do |block|
	Dir.mktmpdir do |root|
		@root = root
		block.call
	end
end

let(:test_path) {File.join(@root, "test.txt")}

it "can create a file" do
	File.write(test_path, "content")
	expect(File).to be(:exist?, test_path)
end
```

## Test Output

In general, tests should not produce output unless there is an error or failure.

### Informational Output

You can use `inform` to print informational messages during tests:

```ruby
it "logs an informational message" do
	rate = copy_data(source, destination)
	inform "Copied data at #{rate}MB/s"
	expect(rate).to be > 0
end
```

This can be useful for debugging or providing context during test runs.

### Console Output

The `sus-fixtures-console` gem provides a way to suppress and capture console output during tests. If you are using code which generates console output, you can use this gem to capture it and assert on it.

## Running Tests

```bash
# Run all tests
bundle exec sus

# Run specific test file
bundle exec sus test/specific_test.rb
```