-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtesting.html
1996 lines (1757 loc) · 116 KB
/
testing.html
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
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Testing Rails Applications — Ruby on Rails Guides</title>
<link rel="stylesheet" type="text/css" href="stylesheets/style.css" data-turbolinks-track="reload">
<link rel="stylesheet" type="text/css" href="stylesheets/print.css" media="print">
<link rel="stylesheet" type="text/css" href="stylesheets/syntaxhighlighter/shCore.css" data-turbolinks-track="reload">
<link rel="stylesheet" type="text/css" href="stylesheets/syntaxhighlighter/shThemeRailsGuides.css" data-turbolinks-track="reload">
<link rel="stylesheet" type="text/css" href="stylesheets/fixes.css" data-turbolinks-track="reload">
<link href="images/favicon.ico" rel="shortcut icon" type="image/x-icon" />
<script src="javascripts/syntaxhighlighter.js" data-turbolinks-track="reload"></script>
<script src="javascripts/turbolinks.js" data-turbolinks-track="reload"></script>
<script src="javascripts/guides.js" data-turbolinks-track="reload"></script>
<script src="javascripts/responsive-tables.js" data-turbolinks-track="reload"></script>
<meta property="og:title" content="Testing Rails Applications — Ruby on Rails Guides" />
<meta name="description" content="Testing Rails ApplicationsThis guide covers built-in mechanisms in Rails for testing your application.After reading this guide, you will know: Rails testing terminology. How to write unit, functional, integration, and system tests for your application. Other popular testing approaches and plugins." />
<meta property="og:description" content="Testing Rails ApplicationsThis guide covers built-in mechanisms in Rails for testing your application.After reading this guide, you will know: Rails testing terminology. How to write unit, functional, integration, and system tests for your application. Other popular testing approaches and plugins." />
<meta property="og:locale" content="en_US" />
<meta property="og:site_name" content="Ruby on Rails Guides" />
<meta property="og:image" content="https://avatars.githubusercontent.com/u/4223" />
<meta property="og:type" content="website" />
</head>
<body class="guide">
<div id="topNav">
<div class="wrapper">
<strong class="more-info-label">공식 웹사이트 <a href="https://rubyonrails.org/">rubyonrails.org:</a> </strong>
<span class="red-button more-info-button">
루비온레일스 웹사이트
</span>
<ul class="more-info-links s-hidden">
<li class="more-info"><a href="https://weblog.rubyonrails.org/">블로그</a></li>
<li class="more-info"><a href="https://guides.rubyonrails.org/">영문가이드</a></li>
<li class="more-info"><a href="https://api.rubyonrails.org/">레일스API</a></li>
<li class="more-info"><a href="https://stackoverflow.com/questions/tagged/ruby-on-rails">질문하기</a></li>
<li class="more-info"><a href="https://github.com/rails/rails">GitHub에서 기여하기</a></li>
</ul>
</div>
</div>
<div id="header">
<div class="wrapper clearfix">
<h1><a href="index.html" title="Return to home page">Guides.rubyonrails.org</a></h1>
<ul class="nav">
<li><a class="nav-item" href="index.html">홈</a></li>
<li class="guides-index guides-index-large">
<a href="index.html" id="guidesMenu" class="guides-index-item nav-item">가이드 인덱스</a>
<div id="guides" class="clearfix" style="display: none;">
<hr />
<div class="guides-section-container">
<div class="guides-section">
<dt>시작하면서</dt>
<dd><a href="getting_started.html">레일스로 시작하기</a></dd>
</div>
<div class="guides-section">
<dt>모델</dt>
<dd><a href="active_record_basics.html">액티브 레코드 기본</a></dd>
<dd><a href="active_record_migrations.html">액티브 레코드 마이그레이션</a></dd>
<dd><a href="active_record_validations.html">액티브 레코드 유효성 검증</a></dd>
<dd><a href="active_record_callbacks.html">액티브 레코드 콜백</a></dd>
<dd><a href="association_basics.html">Active Record Associations</a></dd>
<dd><a href="active_record_querying.html">Active Record Query Interface</a></dd>
</div>
<div class="guides-section">
<dt>Views</dt>
<dd><a href="layouts_and_rendering.html">Layouts and Rendering in Rails</a></dd>
<dd><a href="form_helpers.html">Action View Form Helpers</a></dd>
</div>
<div class="guides-section">
<dt>Controllers</dt>
<dd><a href="action_controller_overview.html">Action Controller Overview</a></dd>
<dd><a href="routing.html">Rails Routing from the Outside In</a></dd>
</div>
<div class="guides-section">
<dt>Other Components</dt>
<dd><a href="active_support_core_extensions.html">Active Support Core Extensions</a></dd>
<dd><a href="action_mailer_basics.html">Action Mailer Basics</a></dd>
<dd><a href="active_job_basics.html">Active Job Basics</a></dd>
<dd><a href="active_storage_overview.html">Active Storage Overview</a></dd>
<dd><a href="action_cable_overview.html">Action Cable Overview</a></dd>
</div>
<div class="guides-section">
<dt>Digging Deeper</dt>
<dd><a href="i18n.html">Rails Internationalization (I18n) API</a></dd>
<dd><a href="testing.html">Testing Rails Applications</a></dd>
<dd><a href="security.html">Securing Rails Applications</a></dd>
<dd><a href="debugging_rails_applications.html">Debugging Rails Applications</a></dd>
<dd><a href="configuring.html">Configuring Rails Applications</a></dd>
<dd><a href="command_line.html">The Rails Command Line</a></dd>
<dd><a href="asset_pipeline.html">The Asset Pipeline</a></dd>
<dd><a href="working_with_javascript_in_rails.html">Working with JavaScript in Rails</a></dd>
<dd><a href="autoloading_and_reloading_constants.html">Autoloading and Reloading Constants (Zeitwerk Mode)</a></dd>
<dd><a href="autoloading_and_reloading_constants_classic_mode.html">Autoloading and Reloading Constants (Classic Mode)</a></dd>
<dd><a href="caching_with_rails.html">Caching with Rails: An Overview</a></dd>
<dd><a href="api_app.html">Using Rails for API-only Applications</a></dd>
</div>
<div class="guides-section">
<dt>Extending Rails</dt>
<dd><a href="rails_on_rack.html">Rails on Rack</a></dd>
<dd><a href="generators.html">Creating and Customizing Rails Generators & Templates</a></dd>
</div>
<div class="guides-section">
<dt>Contributions</dt>
<dd><a href="contributing_to_ruby_on_rails.html">Contributing to Ruby on Rails</a></dd>
<dd><a href="api_documentation_guidelines.html">API Documentation Guidelines</a></dd>
<dd><a href="ruby_on_rails_guides_guidelines.html">Guides Guidelines</a></dd>
</div>
<div class="guides-section">
<dt>Policies</dt>
<dd><a href="maintenance_policy.html">Maintenance Policy</a></dd>
</div>
<div class="guides-section">
<dt>Release Notes</dt>
<dd><a href="upgrading_ruby_on_rails.html">Upgrading Ruby on Rails</a></dd>
<dd><a href="6_0_release_notes.html">Version 6.0 - August 2019</a></dd>
<dd><a href="5_2_release_notes.html">Version 5.2 - April 2018</a></dd>
<dd><a href="5_1_release_notes.html">Version 5.1 - April 2017</a></dd>
<dd><a href="5_0_release_notes.html">Version 5.0 - June 2016</a></dd>
<dd><a href="4_2_release_notes.html">Version 4.2 - December 2014</a></dd>
<dd><a href="4_1_release_notes.html">Version 4.1 - April 2014</a></dd>
<dd><a href="4_0_release_notes.html">Version 4.0 - June 2013</a></dd>
<dd><a href="3_2_release_notes.html">Version 3.2 - January 2012</a></dd>
<dd><a href="3_1_release_notes.html">Version 3.1 - August 2011</a></dd>
<dd><a href="3_0_release_notes.html">Version 3.0 - August 2010</a></dd>
<dd><a href="2_3_release_notes.html">Version 2.3 - March 2009</a></dd>
<dd><a href="2_2_release_notes.html">Version 2.2 - November 2008</a></dd>
</div>
</div>
</div>
</li>
<li><a class="nav-item" href="contributing_to_ruby_on_rails.html">기여하기</a></li>
<li class="guides-index guides-index-small">
<select class="guides-index-item nav-item">
<option value="index.html">가이드 인덱스</option>
<optgroup label="시작하면서">
<option value="getting_started.html">레일스로 시작하기</option>
</optgroup>
<optgroup label="모델">
<option value="active_record_basics.html">액티브 레코드 기본</option>
<option value="active_record_migrations.html">액티브 레코드 마이그레이션</option>
<option value="active_record_validations.html">액티브 레코드 유효성 검증</option>
<option value="active_record_callbacks.html">액티브 레코드 콜백</option>
<option value="association_basics.html">Active Record Associations</option>
<option value="active_record_querying.html">Active Record Query Interface</option>
</optgroup>
<optgroup label="Views">
<option value="layouts_and_rendering.html">Layouts and Rendering in Rails</option>
<option value="form_helpers.html">Action View Form Helpers</option>
</optgroup>
<optgroup label="Controllers">
<option value="action_controller_overview.html">Action Controller Overview</option>
<option value="routing.html">Rails Routing from the Outside In</option>
</optgroup>
<optgroup label="Other Components">
<option value="active_support_core_extensions.html">Active Support Core Extensions</option>
<option value="action_mailer_basics.html">Action Mailer Basics</option>
<option value="active_job_basics.html">Active Job Basics</option>
<option value="active_storage_overview.html">Active Storage Overview</option>
<option value="action_cable_overview.html">Action Cable Overview</option>
</optgroup>
<optgroup label="Digging Deeper">
<option value="i18n.html">Rails Internationalization (I18n) API</option>
<option value="testing.html">Testing Rails Applications</option>
<option value="security.html">Securing Rails Applications</option>
<option value="debugging_rails_applications.html">Debugging Rails Applications</option>
<option value="configuring.html">Configuring Rails Applications</option>
<option value="command_line.html">The Rails Command Line</option>
<option value="asset_pipeline.html">The Asset Pipeline</option>
<option value="working_with_javascript_in_rails.html">Working with JavaScript in Rails</option>
<option value="autoloading_and_reloading_constants.html">Autoloading and Reloading Constants (Zeitwerk Mode)</option>
<option value="autoloading_and_reloading_constants_classic_mode.html">Autoloading and Reloading Constants (Classic Mode)</option>
<option value="caching_with_rails.html">Caching with Rails: An Overview</option>
<option value="api_app.html">Using Rails for API-only Applications</option>
</optgroup>
<optgroup label="Extending Rails">
<option value="rails_on_rack.html">Rails on Rack</option>
<option value="generators.html">Creating and Customizing Rails Generators & Templates</option>
</optgroup>
<optgroup label="Contributions">
<option value="contributing_to_ruby_on_rails.html">Contributing to Ruby on Rails</option>
<option value="api_documentation_guidelines.html">API Documentation Guidelines</option>
<option value="ruby_on_rails_guides_guidelines.html">Guides Guidelines</option>
</optgroup>
<optgroup label="Policies">
<option value="maintenance_policy.html">Maintenance Policy</option>
</optgroup>
<optgroup label="Release Notes">
<option value="upgrading_ruby_on_rails.html">Upgrading Ruby on Rails</option>
<option value="6_0_release_notes.html">Version 6.0 - August 2019</option>
<option value="5_2_release_notes.html">Version 5.2 - April 2018</option>
<option value="5_1_release_notes.html">Version 5.1 - April 2017</option>
<option value="5_0_release_notes.html">Version 5.0 - June 2016</option>
<option value="4_2_release_notes.html">Version 4.2 - December 2014</option>
<option value="4_1_release_notes.html">Version 4.1 - April 2014</option>
<option value="4_0_release_notes.html">Version 4.0 - June 2013</option>
<option value="3_2_release_notes.html">Version 3.2 - January 2012</option>
<option value="3_1_release_notes.html">Version 3.1 - August 2011</option>
<option value="3_0_release_notes.html">Version 3.0 - August 2010</option>
<option value="2_3_release_notes.html">Version 2.3 - March 2009</option>
<option value="2_2_release_notes.html">Version 2.2 - November 2008</option>
</optgroup>
</select>
</li>
</ul>
</div>
</div>
<hr class="hide" />
<div id="feature">
<div class="wrapper">
<h2>Testing Rails Applications</h2><p>This guide covers built-in mechanisms in Rails for testing your application.</p><p>After reading this guide, you will know:</p>
<ul>
<li>Rails testing terminology.</li>
<li>How to write unit, functional, integration, and system tests for your application.</li>
<li>Other popular testing approaches and plugins.</li>
</ul>
<div id="subCol">
<h3 class="chapter"><img src="images/chapters_icon.gif" alt="" />Chapters</h3>
<ol class="chapters">
<li><a href="#why-write-tests-for-your-rails-applications-questionmark">Why Write Tests for your Rails Applications?</a></li>
<li>
<a href="#introduction-to-testing">Introduction to Testing</a>
<ul>
<li><a href="#rails-sets-up-for-testing-from-the-word-go">Rails Sets up for Testing from the Word Go</a></li>
<li><a href="#the-test-environment">The Test Environment</a></li>
<li><a href="#rails-meets-minitest">Rails meets Minitest</a></li>
<li><a href="#available-assertions">Available Assertions</a></li>
<li><a href="#rails-specific-assertions">Rails Specific Assertions</a></li>
<li><a href="#a-brief-note-about-test-cases">A Brief Note About Test Cases</a></li>
<li><a href="#the-rails-test-runner">The Rails Test Runner</a></li>
</ul>
</li>
<li>
<a href="#parallel-testing">Parallel Testing</a>
<ul>
<li><a href="#parallel-testing-with-processes">Parallel testing with processes</a></li>
<li><a href="#parallel-testing-with-threads">Parallel testing with threads</a></li>
</ul>
</li>
<li>
<a href="#the-test-database">The Test Database</a>
<ul>
<li><a href="#maintaining-the-test-database-schema">Maintaining the test database schema</a></li>
<li><a href="#the-low-down-on-fixtures">The Low-Down on Fixtures</a></li>
</ul>
</li>
<li><a href="#model-testing">Model Testing</a></li>
<li>
<a href="#system-testing">System Testing</a>
<ul>
<li><a href="#changing-the-default-settings">Changing the default settings</a></li>
<li><a href="#screenshot-helper">Screenshot Helper</a></li>
<li><a href="#implementing-a-system-test">Implementing a system test</a></li>
</ul>
</li>
<li>
<a href="#integration-testing">Integration Testing</a>
<ul>
<li><a href="#helpers-available-for-integration-tests">Helpers Available for Integration Tests</a></li>
<li><a href="#implementing-an-integration-test">Implementing an integration test</a></li>
</ul>
</li>
<li>
<a href="#functional-tests-for-your-controllers">Functional Tests for Your Controllers</a>
<ul>
<li><a href="#what-to-include-in-your-functional-tests">What to include in your Functional Tests</a></li>
<li><a href="#available-request-types-for-functional-tests">Available Request Types for Functional Tests</a></li>
<li><a href="#testing-xhr-ajax-requests">Testing XHR (AJAX) requests</a></li>
<li><a href="#the-three-hashes-of-the-apocalypse">The Three Hashes of the Apocalypse</a></li>
<li><a href="#instance-variables-available">Instance Variables Available</a></li>
<li><a href="#setting-headers-and-cgi-variables">Setting Headers and CGI variables</a></li>
<li><a href="#testing-flash-notices">Testing <code>flash</code> notices</a></li>
<li><a href="#putting-it-together">Putting it together</a></li>
<li><a href="#test-helpers">Test helpers</a></li>
</ul>
</li>
<li><a href="#testing-routes">Testing Routes</a></li>
<li><a href="#testing-views">Testing Views</a></li>
<li><a href="#testing-helpers">Testing Helpers</a></li>
<li>
<a href="#testing-your-mailers">Testing Your Mailers</a>
<ul>
<li><a href="#keeping-the-postman-in-check">Keeping the Postman in Check</a></li>
<li><a href="#unit-testing">Unit Testing</a></li>
<li><a href="#functional-and-system-testing">Functional and System Testing</a></li>
</ul>
</li>
<li>
<a href="#testing-jobs">Testing Jobs</a>
<ul>
<li><a href="#a-basic-test-case">A Basic Test Case</a></li>
<li><a href="#custom-assertions-and-testing-jobs-inside-other-components">Custom Assertions And Testing Jobs Inside Other Components</a></li>
<li><a href="#asserting-time-arguments-in-jobs">Asserting Time Arguments in Jobs</a></li>
</ul>
</li>
<li>
<a href="#testing-action-cable">Testing Action Cable</a>
<ul>
<li><a href="#connection-test-case">Connection Test Case</a></li>
<li><a href="#channel-test-case">Channel Test Case</a></li>
<li><a href="#custom-assertions-and-testing-broadcasts-inside-other-components">Custom Assertions And Testing Broadcasts Inside Other Components</a></li>
</ul>
</li>
<li>
<a href="#additional-testing-resources">Additional Testing Resources</a>
<ul>
<li><a href="#testing-time-dependent-code">Testing Time-Dependent Code</a></li>
</ul>
</li>
</ol>
</div>
</div>
</div>
<div id="container">
<div class="wrapper">
<div id="mainCol">
<h3 id="why-write-tests-for-your-rails-applications-questionmark"><a class="anchorlink" href="#why-write-tests-for-your-rails-applications-questionmark">1 Why Write Tests for your Rails Applications?</a></h3><p>Rails makes it super easy to write your tests. It starts by producing skeleton test code while you are creating your models and controllers.</p><p>By running your Rails tests you can ensure your code adheres to the desired functionality even after some major code refactoring.</p><p>Rails tests can also simulate browser requests and thus you can test your application's response without having to test it through your browser.</p><h3 id="introduction-to-testing"><a class="anchorlink" href="#introduction-to-testing">2 Introduction to Testing</a></h3><p>Testing support was woven into the Rails fabric from the beginning. It wasn't an "oh! let's bolt on support for running tests because they're new and cool" epiphany.</p><h4 id="rails-sets-up-for-testing-from-the-word-go"><a class="anchorlink" href="#rails-sets-up-for-testing-from-the-word-go">2.1 Rails Sets up for Testing from the Word Go</a></h4><p>Rails creates a <code>test</code> directory for you as soon as you create a Rails project using <code>rails new</code> <em>application_name</em>. If you list the contents of this directory then you shall see:</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
$ ls -F test
application_system_test_case.rb controllers/ helpers/ mailers/ system/
channels/ fixtures/ integration/ models/ test_helper.rb
</pre>
</div>
<p>The <code>helpers</code>, <code>mailers</code>, and <code>models</code> directories are meant to hold tests for view helpers, mailers, and models, respectively. The <code>channels</code> directory is meant to hold tests for Action Cable connection and channels. The <code>controllers</code> directory is meant to hold tests for controllers, routes, and views. The <code>integration</code> directory is meant to hold tests for interactions between controllers.</p><p>The system test directory holds system tests, which are used for full browser
testing of your application. System tests allow you to test your application
the way your users experience it and help you test your JavaScript as well.
System tests inherit from Capybara and perform in browser tests for your
application.</p><p>Fixtures are a way of organizing test data; they reside in the <code>fixtures</code> directory.</p><p>A <code>jobs</code> directory will also be created when an associated test is first generated.</p><p>The <code>test_helper.rb</code> file holds the default configuration for your tests.</p><p>The <code>application_system_test_case.rb</code> holds the default configuration for your system
tests.</p><h4 id="the-test-environment"><a class="anchorlink" href="#the-test-environment">2.2 The Test Environment</a></h4><p>By default, every Rails application has three environments: development, test, and production.</p><p>Each environment's configuration can be modified similarly. In this case, we can modify our test environment by changing the options found in <code>config/environments/test.rb</code>.</p><div class="note"><p>Your tests are run under <code>RAILS_ENV=test</code>.</p></div><h4 id="rails-meets-minitest"><a class="anchorlink" href="#rails-meets-minitest">2.3 Rails meets Minitest</a></h4><p>If you remember, we used the <code>rails generate model</code> command in the
<a href="getting_started.html">Getting Started with Rails</a> guide. We created our first
model, and among other things it created test stubs in the <code>test</code> directory:</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
$ rails generate model article title:string body:text
...
create app/models/article.rb
create test/models/article_test.rb
create test/fixtures/articles.yml
...
</pre>
</div>
<p>The default test stub in <code>test/models/article_test.rb</code> looks like this:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
require 'test_helper'
class ArticleTest < ActiveSupport::TestCase
# test "the truth" do
# assert true
# end
end
</pre>
</div>
<p>A line by line examination of this file will help get you oriented to Rails testing code and terminology.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
require 'test_helper'
</pre>
</div>
<p>By requiring this file, <code>test_helper.rb</code> the default configuration to run our tests is loaded. We will include this with all the tests we write, so any methods added to this file are available to all our tests.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class ArticleTest < ActiveSupport::TestCase
</pre>
</div>
<p>The <code>ArticleTest</code> class defines a <em>test case</em> because it inherits from <code>ActiveSupport::TestCase</code>. <code>ArticleTest</code> thus has all the methods available from <code>ActiveSupport::TestCase</code>. Later in this guide, we'll see some of the methods it gives us.</p><p>Any method defined within a class inherited from <code>Minitest::Test</code>
(which is the superclass of <code>ActiveSupport::TestCase</code>) that begins with <code>test_</code> is simply called a test. So, methods defined as <code>test_password</code> and <code>test_valid_password</code> are legal test names and are run automatically when the test case is run.</p><p>Rails also adds a <code>test</code> method that takes a test name and a block. It generates a normal <code>Minitest::Unit</code> test with method names prefixed with <code>test_</code>. So you don't have to worry about naming the methods, and you can write something like:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
test "the truth" do
assert true
end
</pre>
</div>
<p>Which is approximately the same as writing this:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
def test_the_truth
assert true
end
</pre>
</div>
<p>Although you can still use regular method definitions, using the <code>test</code> macro allows for a more readable test name.</p><div class="note"><p>The method name is generated by replacing spaces with underscores. The result does not need to be a valid Ruby identifier though, the name may contain punctuation characters etc. That's because in Ruby technically any string may be a method name. This may require use of <code>define_method</code> and <code>send</code> calls to function properly, but formally there's little restriction on the name.</p></div><p>Next, let's look at our first assertion:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
assert true
</pre>
</div>
<p>An assertion is a line of code that evaluates an object (or expression) for expected results. For example, an assertion can check:</p>
<ul>
<li>does this value = that value?</li>
<li>is this object nil?</li>
<li>does this line of code throw an exception?</li>
<li>is the user's password greater than 5 characters?</li>
</ul>
<p>Every test may contain one or more assertions, with no restriction as to how many assertions are allowed. Only when all the assertions are successful will the test pass.</p><h5 id="your-first-failing-test"><a class="anchorlink" href="#your-first-failing-test">2.3.1 Your first failing test</a></h5><p>To see how a test failure is reported, you can add a failing test to the <code>article_test.rb</code> test case.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
test "should not save article without title" do
article = Article.new
assert_not article.save
end
</pre>
</div>
<p>Let us run this newly added test (where <code>6</code> is the number of line where the test is defined).</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
$ rails test test/models/article_test.rb:6
Run options: --seed 44656
# Running:
F
Failure:
ArticleTest#test_should_not_save_article_without_title [/path/to/blog/test/models/article_test.rb:6]:
Expected true to be nil or false
rails test test/models/article_test.rb:6
Finished in 0.023918s, 41.8090 runs/s, 41.8090 assertions/s.
1 runs, 1 assertions, 1 failures, 0 errors, 0 skips
</pre>
</div>
<p>In the output, <code>F</code> denotes a failure. You can see the corresponding trace shown under <code>Failure</code> along with the name of the failing test. The next few lines contain the stack trace followed by a message that mentions the actual value and the expected value by the assertion. The default assertion messages provide just enough information to help pinpoint the error. To make the assertion failure message more readable, every assertion provides an optional message parameter, as shown here:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
test "should not save article without title" do
article = Article.new
assert_not article.save, "Saved the article without a title"
end
</pre>
</div>
<p>Running this test shows the friendlier assertion message:</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
Failure:
ArticleTest#test_should_not_save_article_without_title [/path/to/blog/test/models/article_test.rb:6]:
Saved the article without a title
</pre>
</div>
<p>Now to get this test to pass we can add a model level validation for the <em>title</em> field.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class Article < ApplicationRecord
validates :title, presence: true
end
</pre>
</div>
<p>Now the test should pass. Let us verify by running the test again:</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
$ rails test test/models/article_test.rb:6
Run options: --seed 31252
# Running:
.
Finished in 0.027476s, 36.3952 runs/s, 36.3952 assertions/s.
1 runs, 1 assertions, 0 failures, 0 errors, 0 skips
</pre>
</div>
<p>Now, if you noticed, we first wrote a test which fails for a desired
functionality, then we wrote some code which adds the functionality and finally
we ensured that our test passes. This approach to software development is
referred to as
<a href="http://c2.com/cgi/wiki?TestDrivenDevelopment"><em>Test-Driven Development</em> (TDD)</a>.</p><h5 id="what-an-error-looks-like"><a class="anchorlink" href="#what-an-error-looks-like">2.3.2 What an error looks like</a></h5><p>To see how an error gets reported, here's a test containing an error:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
test "should report error" do
# some_undefined_variable is not defined elsewhere in the test case
some_undefined_variable
assert true
end
</pre>
</div>
<p>Now you can see even more output in the console from running the tests:</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
$ rails test test/models/article_test.rb
Run options: --seed 1808
# Running:
.E
Error:
ArticleTest#test_should_report_error:
NameError: undefined local variable or method 'some_undefined_variable' for #<ArticleTest:0x007fee3aa71798>
test/models/article_test.rb:11:in 'block in <class:ArticleTest>'
rails test test/models/article_test.rb:9
Finished in 0.040609s, 49.2500 runs/s, 24.6250 assertions/s.
2 runs, 1 assertions, 0 failures, 1 errors, 0 skips
</pre>
</div>
<p>Notice the 'E' in the output. It denotes a test with error.</p><div class="note"><p>The execution of each test method stops as soon as any error or an
assertion failure is encountered, and the test suite continues with the next
method. All test methods are executed in random order. The
<a href="configuring.html#configuring-active-support"><code>config.active_support.test_order</code> option</a>
can be used to configure test order.</p></div><p>When a test fails you are presented with the corresponding backtrace. By default
Rails filters that backtrace and will only print lines relevant to your
application. This eliminates the framework noise and helps to focus on your
code. However there are situations when you want to see the full
backtrace. Set the <code>-b</code> (or <code>--backtrace</code>) argument to enable this behavior:</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
$ rails test -b test/models/article_test.rb
</pre>
</div>
<p>If we want this test to pass we can modify it to use <code>assert_raises</code> like so:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
test "should report error" do
# some_undefined_variable is not defined elsewhere in the test case
assert_raises(NameError) do
some_undefined_variable
end
end
</pre>
</div>
<p>This test should now pass.</p><h4 id="available-assertions"><a class="anchorlink" href="#available-assertions">2.4 Available Assertions</a></h4><p>By now you've caught a glimpse of some of the assertions that are available. Assertions are the worker bees of testing. They are the ones that actually perform the checks to ensure that things are going as planned.</p><p>Here's an extract of the assertions you can use with
<a href="https://github.com/seattlerb/minitest"><code>Minitest</code></a>, the default testing library
used by Rails. The <code>[msg]</code> parameter is an optional string message you can
specify to make your test failure messages clearer.</p>
<table>
<thead>
<tr>
<th>Assertion</th>
<th>Purpose</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>assert( test, [msg] )</code></td>
<td>Ensures that <code>test</code> is true.</td>
</tr>
<tr>
<td><code>assert_not( test, [msg] )</code></td>
<td>Ensures that <code>test</code> is false.</td>
</tr>
<tr>
<td><code>assert_equal( expected, actual, [msg] )</code></td>
<td>Ensures that <code>expected == actual</code> is true.</td>
</tr>
<tr>
<td><code>assert_not_equal( expected, actual, [msg] )</code></td>
<td>Ensures that <code>expected != actual</code> is true.</td>
</tr>
<tr>
<td><code>assert_same( expected, actual, [msg] )</code></td>
<td>Ensures that <code>expected.equal?(actual)</code> is true.</td>
</tr>
<tr>
<td><code>assert_not_same( expected, actual, [msg] )</code></td>
<td>Ensures that <code>expected.equal?(actual)</code> is false.</td>
</tr>
<tr>
<td><code>assert_nil( obj, [msg] )</code></td>
<td>Ensures that <code>obj.nil?</code> is true.</td>
</tr>
<tr>
<td><code>assert_not_nil( obj, [msg] )</code></td>
<td>Ensures that <code>obj.nil?</code> is false.</td>
</tr>
<tr>
<td><code>assert_empty( obj, [msg] )</code></td>
<td>Ensures that <code>obj</code> is <code>empty?</code>.</td>
</tr>
<tr>
<td><code>assert_not_empty( obj, [msg] )</code></td>
<td>Ensures that <code>obj</code> is not <code>empty?</code>.</td>
</tr>
<tr>
<td><code>assert_match( regexp, string, [msg] )</code></td>
<td>Ensures that a string matches the regular expression.</td>
</tr>
<tr>
<td><code>assert_no_match( regexp, string, [msg] )</code></td>
<td>Ensures that a string doesn't match the regular expression.</td>
</tr>
<tr>
<td><code>assert_includes( collection, obj, [msg] )</code></td>
<td>Ensures that <code>obj</code> is in <code>collection</code>.</td>
</tr>
<tr>
<td><code>assert_not_includes( collection, obj, [msg] )</code></td>
<td>Ensures that <code>obj</code> is not in <code>collection</code>.</td>
</tr>
<tr>
<td><code>assert_in_delta( expected, actual, [delta], [msg] )</code></td>
<td>Ensures that the numbers <code>expected</code> and <code>actual</code> are within <code>delta</code> of each other.</td>
</tr>
<tr>
<td><code>assert_not_in_delta( expected, actual, [delta], [msg] )</code></td>
<td>Ensures that the numbers <code>expected</code> and <code>actual</code> are not within <code>delta</code> of each other.</td>
</tr>
<tr>
<td><code>assert_in_epsilon ( expected, actual, [epsilon], [msg] )</code></td>
<td>Ensures that the numbers <code>expected</code> and <code>actual</code> have a relative error less than <code>epsilon</code>.</td>
</tr>
<tr>
<td><code>assert_not_in_epsilon ( expected, actual, [epsilon], [msg] )</code></td>
<td>Ensures that the numbers <code>expected</code> and <code>actual</code> don't have a relative error less than <code>epsilon</code>.</td>
</tr>
<tr>
<td><code>assert_throws( symbol, [msg] ) { block }</code></td>
<td>Ensures that the given block throws the symbol.</td>
</tr>
<tr>
<td><code>assert_raises( exception1, exception2, ... ) { block }</code></td>
<td>Ensures that the given block raises one of the given exceptions.</td>
</tr>
<tr>
<td><code>assert_instance_of( class, obj, [msg] )</code></td>
<td>Ensures that <code>obj</code> is an instance of <code>class</code>.</td>
</tr>
<tr>
<td><code>assert_not_instance_of( class, obj, [msg] )</code></td>
<td>Ensures that <code>obj</code> is not an instance of <code>class</code>.</td>
</tr>
<tr>
<td><code>assert_kind_of( class, obj, [msg] )</code></td>
<td>Ensures that <code>obj</code> is an instance of <code>class</code> or is descending from it.</td>
</tr>
<tr>
<td><code>assert_not_kind_of( class, obj, [msg] )</code></td>
<td>Ensures that <code>obj</code> is not an instance of <code>class</code> and is not descending from it.</td>
</tr>
<tr>
<td><code>assert_respond_to( obj, symbol, [msg] )</code></td>
<td>Ensures that <code>obj</code> responds to <code>symbol</code>.</td>
</tr>
<tr>
<td><code>assert_not_respond_to( obj, symbol, [msg] )</code></td>
<td>Ensures that <code>obj</code> does not respond to <code>symbol</code>.</td>
</tr>
<tr>
<td><code>assert_operator( obj1, operator, [obj2], [msg] )</code></td>
<td>Ensures that <code>obj1.operator(obj2)</code> is true.</td>
</tr>
<tr>
<td><code>assert_not_operator( obj1, operator, [obj2], [msg] )</code></td>
<td>Ensures that <code>obj1.operator(obj2)</code> is false.</td>
</tr>
<tr>
<td><code>assert_predicate ( obj, predicate, [msg] )</code></td>
<td>Ensures that <code>obj.predicate</code> is true, e.g. <code>assert_predicate str, :empty?</code>
</td>
</tr>
<tr>
<td><code>assert_not_predicate ( obj, predicate, [msg] )</code></td>
<td>Ensures that <code>obj.predicate</code> is false, e.g. <code>assert_not_predicate str, :empty?</code>
</td>
</tr>
<tr>
<td><code>flunk( [msg] )</code></td>
<td>Ensures failure. This is useful to explicitly mark a test that isn't finished yet.</td>
</tr>
</tbody>
</table>
<p>The above are a subset of assertions that minitest supports. For an exhaustive &
more up-to-date list, please check
<a href="http://docs.seattlerb.org/minitest/">Minitest API documentation</a>, specifically
<a href="http://docs.seattlerb.org/minitest/Minitest/Assertions.html"><code>Minitest::Assertions</code></a>.</p><p>Because of the modular nature of the testing framework, it is possible to create your own assertions. In fact, that's exactly what Rails does. It includes some specialized assertions to make your life easier.</p><div class="note"><p>Creating your own assertions is an advanced topic that we won't cover in this tutorial.</p></div><h4 id="rails-specific-assertions"><a class="anchorlink" href="#rails-specific-assertions">2.5 Rails Specific Assertions</a></h4><p>Rails adds some custom assertions of its own to the <code>minitest</code> framework:</p>
<table>
<thead>
<tr>
<th>Assertion</th>
<th>Purpose</th>
</tr>
</thead>
<tbody>
<tr>
<td><a href="https://api.rubyonrails.org/6-0-stable/classes/ActiveSupport/Testing/Assertions.html#method-i-assert_difference"><code>assert_difference(expressions, difference = 1, message = nil) {...}</code></a></td>
<td>Test numeric difference between the return value of an expression as a result of what is evaluated in the yielded block.</td>
</tr>
<tr>
<td><a href="https://api.rubyonrails.org/6-0-stable/classes/ActiveSupport/Testing/Assertions.html#method-i-assert_no_difference"><code>assert_no_difference(expressions, message = nil, &block)</code></a></td>
<td>Asserts that the numeric result of evaluating an expression is not changed before and after invoking the passed in block.</td>
</tr>
<tr>
<td><a href="https://api.rubyonrails.org/6-0-stable/classes/ActiveSupport/Testing/Assertions.html#method-i-assert_changes"><code>assert_changes(expressions, message = nil, from:, to:, &block)</code></a></td>
<td>Test that the result of evaluating an expression is changed after invoking the passed in block.</td>
</tr>
<tr>
<td><a href="https://api.rubyonrails.org/6-0-stable/classes/ActiveSupport/Testing/Assertions.html#method-i-assert_no_changes"><code>assert_no_changes(expressions, message = nil, &block)</code></a></td>
<td>Test the result of evaluating an expression is not changed after invoking the passed in block.</td>
</tr>
<tr>
<td><a href="https://api.rubyonrails.org/6-0-stable/classes/ActiveSupport/Testing/Assertions.html#method-i-assert_nothing_raised"><code>assert_nothing_raised { block }</code></a></td>
<td>Ensures that the given block doesn't raise any exceptions.</td>
</tr>
<tr>
<td><a href="https://api.rubyonrails.org/6-0-stable/classes/ActionDispatch/Assertions/RoutingAssertions.html#method-i-assert_recognizes"><code>assert_recognizes(expected_options, path, extras={}, message=nil)</code></a></td>
<td>Asserts that the routing of the given path was handled correctly and that the parsed options (given in the expected_options hash) match path. Basically, it asserts that Rails recognizes the route given by expected_options.</td>
</tr>
<tr>
<td><a href="https://api.rubyonrails.org/6-0-stable/classes/ActionDispatch/Assertions/RoutingAssertions.html#method-i-assert_generates"><code>assert_generates(expected_path, options, defaults={}, extras = {}, message=nil)</code></a></td>
<td>Asserts that the provided options can be used to generate the provided path. This is the inverse of assert_recognizes. The extras parameter is used to tell the request the names and values of additional request parameters that would be in a query string. The message parameter allows you to specify a custom error message for assertion failures.</td>
</tr>
<tr>
<td><a href="https://api.rubyonrails.org/6-0-stable/classes/ActionDispatch/Assertions/ResponseAssertions.html#method-i-assert_response"><code>assert_response(type, message = nil)</code></a></td>
<td>Asserts that the response comes with a specific status code. You can specify <code>:success</code> to indicate 200-299, <code>:redirect</code> to indicate 300-399, <code>:missing</code> to indicate 404, or <code>:error</code> to match the 500-599 range. You can also pass an explicit status number or its symbolic equivalent. For more information, see <a href="http://rubydoc.info/github/rack/rack/master/Rack/Utils#HTTP_STATUS_CODES-constant">full list of status codes</a> and how their <a href="https://rubydoc.info/github/rack/rack/master/Rack/Utils#SYMBOL_TO_STATUS_CODE-constant">mapping</a> works.</td>
</tr>
<tr>
<td><a href="https://api.rubyonrails.org/6-0-stable/classes/ActionDispatch/Assertions/ResponseAssertions.html#method-i-assert_redirected_to"><code>assert_redirected_to(options = {}, message=nil)</code></a></td>
<td>Asserts that the redirection options passed in match those of the redirect called in the latest action. This match can be partial, such that <code>assert_redirected_to(controller: "weblog")</code> will also match the redirection of <code>redirect_to(controller: "weblog", action: "show")</code> and so on. You can also pass named routes such as <code>assert_redirected_to root_path</code> and Active Record objects such as <code>assert_redirected_to @article</code>.</td>
</tr>
</tbody>
</table>
<p>You'll see the usage of some of these assertions in the next chapter.</p><h4 id="a-brief-note-about-test-cases"><a class="anchorlink" href="#a-brief-note-about-test-cases">2.6 A Brief Note About Test Cases</a></h4><p>All the basic assertions such as <code>assert_equal</code> defined in <code>Minitest::Assertions</code> are also available in the classes we use in our own test cases. In fact, Rails provides the following classes for you to inherit from:</p>
<ul>
<li><a href="https://api.rubyonrails.org/6-0-stable/classes/ActiveSupport/TestCase.html"><code>ActiveSupport::TestCase</code></a></li>
<li><a href="https://api.rubyonrails.org/6-0-stable/classes/ActionMailer/TestCase.html"><code>ActionMailer::TestCase</code></a></li>
<li><a href="https://api.rubyonrails.org/6-0-stable/classes/ActionView/TestCase.html"><code>ActionView::TestCase</code></a></li>
<li><a href="https://api.rubyonrails.org/6-0-stable/classes/ActiveJob/TestCase.html"><code>ActiveJob::TestCase</code></a></li>
<li><a href="https://api.rubyonrails.org/6-0-stable/classes/ActionDispatch/IntegrationTest.html"><code>ActionDispatch::IntegrationTest</code></a></li>
<li><a href="https://api.rubyonrails.org/6-0-stable/classes/ActionDispatch/SystemTestCase.html"><code>ActionDispatch::SystemTestCase</code></a></li>
<li><a href="https://api.rubyonrails.org/6-0-stable/classes/Rails/Generators/TestCase.html"><code>Rails::Generators::TestCase</code></a></li>
</ul>
<p>Each of these classes include <code>Minitest::Assertions</code>, allowing us to use all of the basic assertions in our tests.</p><div class="note"><p>For more information on <code>Minitest</code>, refer to <a href="http://docs.seattlerb.org/minitest">its
documentation</a>.</p></div><h4 id="the-rails-test-runner"><a class="anchorlink" href="#the-rails-test-runner">2.7 The Rails Test Runner</a></h4><p>We can run all of our tests at once by using the <code>rails test</code> command.</p><p>Or we can run a single test file by passing the <code>rails test</code> command the filename containing the test cases.</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
$ rails test test/models/article_test.rb
Run options: --seed 1559
# Running:
..
Finished in 0.027034s, 73.9810 runs/s, 110.9715 assertions/s.
2 runs, 3 assertions, 0 failures, 0 errors, 0 skips
</pre>
</div>
<p>This will run all test methods from the test case.</p><p>You can also run a particular test method from the test case by providing the
<code>-n</code> or <code>--name</code> flag and the test's method name.</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
$ rails test test/models/article_test.rb -n test_the_truth
Run options: -n test_the_truth --seed 43583
# Running:
.
Finished tests in 0.009064s, 110.3266 tests/s, 110.3266 assertions/s.
1 tests, 1 assertions, 0 failures, 0 errors, 0 skips
</pre>
</div>
<p>You can also run a test at a specific line by providing the line number.</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
$ rails test test/models/article_test.rb:6 # run specific test and line
</pre>
</div>
<p>You can also run an entire directory of tests by providing the path to the directory.</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
$ rails test test/controllers # run all tests from specific directory
</pre>
</div>
<p>The test runner also provides a lot of other features like failing fast, deferring test output
at the end of test run and so on. Check the documentation of the test runner as follows:</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
$ rails test -h
Usage: rails test [options] [files or directories]
You can run a single test by appending a line number to a filename:
rails test test/models/user_test.rb:27
You can run multiple files and directories at the same time:
rails test test/controllers test/integration/login_test.rb
By default test failures and errors are reported inline during a run.
minitest options:
-h, --help Display this help.
--no-plugins Bypass minitest plugin auto-loading (or set $MT_NO_PLUGINS).
-s, --seed SEED Sets random seed. Also via env. Eg: SEED=n rake
-v, --verbose Verbose. Show progress processing files.
-n, --name PATTERN Filter run on /regexp/ or string.
--exclude PATTERN Exclude /regexp/ or string from run.
Known extensions: rails, pride
-w, --warnings Run with Ruby warnings enabled
-e, --environment ENV Run tests in the ENV environment
-b, --backtrace Show the complete backtrace
-d, --defer-output Output test failures and errors after the test run
-f, --fail-fast Abort test run on first failure or error
-c, --[no-]color Enable color in the output
-p, --pride Pride. Show your testing pride!
</pre>
</div>
<h3 id="parallel-testing"><a class="anchorlink" href="#parallel-testing">3 Parallel Testing</a></h3><p>Parallel testing allows you to parallelize your test suite. While forking processes is the
default method, threading is supported as well. Running tests in parallel reduces the time it
takes your entire test suite to run.</p><h4 id="parallel-testing-with-processes"><a class="anchorlink" href="#parallel-testing-with-processes">3.1 Parallel testing with processes</a></h4><p>The default parallelization method is to fork processes using Ruby's DRb system. The processes
are forked based on the number of workers provided. The default number is the actual core count
on the machine you are on, but can be changed by the number passed to the parallelize method.</p><p>To enable parallelization add the following to your <code>test_helper.rb</code>:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class ActiveSupport::TestCase
parallelize(workers: 2)
end
</pre>
</div>
<p>The number of workers passed is the number of times the process will be forked. You may want to
parallelize your local test suite differently from your CI, so an environment variable is provided
to be able to easily change the number of workers a test run should use:</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
PARALLEL_WORKERS=15 rails test
</pre>
</div>
<p>When parallelizing tests, Active Record automatically handles creating a database and loading the schema into the database for each
process. The databases will be suffixed with the number corresponding to the worker. For example, if you
have 2 workers the tests will create <code>test-database-0</code> and <code>test-database-1</code> respectively.</p><p>If the number of workers passed is 1 or fewer the processes will not be forked and the tests will not
be parallelized and the tests will use the original <code>test-database</code> database.</p><p>Two hooks are provided, one runs when the process is forked, and one runs before the forked process is closed.
These can be useful if your app uses multiple databases or perform other tasks that depend on the number of
workers.</p><p>The <code>parallelize_setup</code> method is called right after the processes are forked. The <code>parallelize_teardown</code> method
is called right before the processes are closed.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class ActiveSupport::TestCase
parallelize_setup do |worker|
# setup databases
end
parallelize_teardown do |worker|
# cleanup databases
end
parallelize(workers: :number_of_processors)
end
</pre>
</div>
<p>These methods are not needed or available when using parallel testing with threads.</p><h4 id="parallel-testing-with-threads"><a class="anchorlink" href="#parallel-testing-with-threads">3.2 Parallel testing with threads</a></h4><p>If you prefer using threads or are using JRuby, a threaded parallelization option is provided. The threaded
parallelizer is backed by Minitest's <code>Parallel::Executor</code>.</p><p>To change the parallelization method to use threads over forks put the following in your <code>test_helper.rb</code></p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class ActiveSupport::TestCase
parallelize(workers: :number_of_processors, with: :threads)
end
</pre>
</div>
<p>Rails applications generated from JRuby will automatically include the <code>with: :threads</code> option.</p><p>The number of workers passed to <code>parallelize</code> determines the number of threads the tests will use. You may
want to parallelize your local test suite differently from your CI, so an environment variable is provided
to be able to easily change the number of workers a test run should use:</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
PARALLEL_WORKERS=15 rails test
</pre>
</div>
<h3 id="the-test-database"><a class="anchorlink" href="#the-test-database">4 The Test Database</a></h3><p>Just about every Rails application interacts heavily with a database and, as a result, your tests will need a database to interact with as well. To write efficient tests, you'll need to understand how to set up this database and populate it with sample data.</p><p>By default, every Rails application has three environments: development, test, and production. The database for each one of them is configured in <code>config/database.yml</code>.</p><p>A dedicated test database allows you to set up and interact with test data in isolation. This way your tests can mangle test data with confidence, without worrying about the data in the development or production databases.</p><h4 id="maintaining-the-test-database-schema"><a class="anchorlink" href="#maintaining-the-test-database-schema">4.1 Maintaining the test database schema</a></h4><p>In order to run your tests, your test database will need to have the current
structure. The test helper checks whether your test database has any pending
migrations. It will try to load your <code>db/schema.rb</code> or <code>db/structure.sql</code>
into the test database. If migrations are still pending, an error will be
raised. Usually this indicates that your schema is not fully migrated. Running
the migrations against the development database (<code>rails db:migrate</code>) will
bring the schema up to date.</p><div class="note"><p>If there were modifications to existing migrations, the test database needs to
be rebuilt. This can be done by executing <code>rails db:test:prepare</code>.</p></div><h4 id="the-low-down-on-fixtures"><a class="anchorlink" href="#the-low-down-on-fixtures">4.2 The Low-Down on Fixtures</a></h4><p>For good tests, you'll need to give some thought to setting up test data.
In Rails, you can handle this by defining and customizing fixtures.
You can find comprehensive documentation in the <a href="https://api.rubyonrails.org/6-0-stable/classes/ActiveRecord/FixtureSet.html">Fixtures API documentation</a>.</p><h5 id="what-are-fixtures-questionmark"><a class="anchorlink" href="#what-are-fixtures-questionmark">4.2.1 What Are Fixtures?</a></h5><p><em>Fixtures</em> is a fancy word for sample data. Fixtures allow you to populate your testing database with predefined data before your tests run. Fixtures are database independent and written in YAML. There is one file per model.</p><div class="note"><p>Fixtures are not designed to create every object that your tests need, and are best managed when only used for default data that can be applied to the common case.</p></div><p>You'll find fixtures under your <code>test/fixtures</code> directory. When you run <code>rails generate model</code> to create a new model, Rails automatically creates fixture stubs in this directory.</p><h5 id="yaml"><a class="anchorlink" href="#yaml">4.2.2 YAML</a></h5><p>YAML-formatted fixtures are a human-friendly way to describe your sample data. These types of fixtures have the <strong>.yml</strong> file extension (as in <code>users.yml</code>).</p><p>Here's a sample YAML fixture file:</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
# lo & behold! I am a YAML comment!
david:
name: David Heinemeier Hansson
birthday: 1979-10-15
profession: Systems development
steve:
name: Steve Ross Kellock
birthday: 1974-09-27
profession: guy with keyboard
</pre>
</div>
<p>Each fixture is given a name followed by an indented list of colon-separated key/value pairs. Records are typically separated by a blank line. You can place comments in a fixture file by using the # character in the first column.</p><p>If you are working with <a href="/association_basics.html">associations</a>, you can
define a reference node between two different fixtures. Here's an example with
a <code>belongs_to</code>/<code>has_many</code> association:</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
# In fixtures/categories.yml
about:
name: About
# In fixtures/articles.yml
first:
title: Welcome to Rails!
body: Hello world!
category: about
</pre>
</div>
<p>Notice the <code>category</code> key of the <code>first</code> article found in <code>fixtures/articles.yml</code> has a value of <code>about</code>. This tells Rails to load the category <code>about</code> found in <code>fixtures/categories.yml</code>.</p><div class="note"><p>For associations to reference one another by name, you can use the fixture name instead of specifying the <code>id:</code> attribute on the associated fixtures. Rails will auto assign a primary key to be consistent between runs. For more information on this association behavior please read the <a href="https://api.rubyonrails.org/6-0-stable/classes/ActiveRecord/FixtureSet.html">Fixtures API documentation</a>.</p></div><h5 id="erb-in-it-up"><a class="anchorlink" href="#erb-in-it-up">4.2.3 ERB'in It Up</a></h5><p>ERB allows you to embed Ruby code within templates. The YAML fixture format is pre-processed with ERB when Rails loads fixtures. This allows you to use Ruby to help you generate some sample data. For example, the following code generates a thousand users:</p><div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
<% 1000.times do |n| %>
user_<%= n %>:
username: <%= "user#{n}" %>
email: <%= "user#{n}@example.com" %>
<% end %>
</pre>
</div>
<h5 id="fixtures-in-action"><a class="anchorlink" href="#fixtures-in-action">4.2.4 Fixtures in Action</a></h5><p>Rails automatically loads all fixtures from the <code>test/fixtures</code> directory by
default. Loading involves three steps:</p>
<ol>
<li>Remove any existing data from the table corresponding to the fixture</li>
<li>Load the fixture data into the table</li>
<li>Dump the fixture data into a method in case you want to access it directly</li>
</ol>
<div class="info"><p>In order to remove existing data from the database, Rails tries to disable referential integrity triggers (like foreign keys and check constraints). If you are getting annoying permission errors on running tests, make sure the database user has privilege to disable these triggers in testing environment. (In PostgreSQL, only superusers can disable all triggers. Read more about PostgreSQL permissions <a href="http://blog.endpoint.com/2012/10/postgres-system-triggers-error.html">here</a>).</p></div><h5 id="fixtures-are-active-record-objects"><a class="anchorlink" href="#fixtures-are-active-record-objects">4.2.5 Fixtures are Active Record objects</a></h5><p>Fixtures are instances of Active Record. As mentioned in point #3 above, you can access the object directly because it is automatically available as a method whose scope is local of the test case. For example:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
# this will return the User object for the fixture named david
users(:david)
# this will return the property for david called id
users(:david).id
# one can also access methods available on the User class
david = users(:david)
david.call(david.partner)
</pre>
</div>
<p>To get multiple fixtures at once, you can pass in a list of fixture names. For example:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
# this will return an array containing the fixtures david and steve
users(:david, :steve)
</pre>
</div>
<h3 id="model-testing"><a class="anchorlink" href="#model-testing">5 Model Testing</a></h3><p>Model tests are used to test the various models of your application.</p><p>Rails model tests are stored under the <code>test/models</code> directory. Rails provides
a generator to create a model test skeleton for you.</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
$ rails generate test_unit:model article title:string body:text
create test/models/article_test.rb
create test/fixtures/articles.yml
</pre>
</div>
<p>Model tests don't have their own superclass like <code>ActionMailer::TestCase</code> instead they inherit from <a href="https://api.rubyonrails.org/6-0-stable/classes/ActiveSupport/TestCase.html"><code>ActiveSupport::TestCase</code></a>.</p><h3 id="system-testing"><a class="anchorlink" href="#system-testing">6 System Testing</a></h3><p>System tests allow you to test user interactions with your application, running tests
in either a real or a headless browser. System tests use Capybara under the hood.</p><p>For creating Rails system tests, you use the <code>test/system</code> directory in your
application. Rails provides a generator to create a system test skeleton for you.</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
$ rails generate system_test users
invoke test_unit
create test/system/users_test.rb
</pre>
</div>
<p>Here's what a freshly generated system test looks like:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
require "application_system_test_case"
class UsersTest < ApplicationSystemTestCase
# test "visiting the index" do
# visit users_url
#
# assert_selector "h1", text: "Users"
# end
end
</pre>
</div>
<p>By default, system tests are run with the Selenium driver, using the Chrome
browser, and a screen size of 1400x1400. The next section explains how to