-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtesting.html
More file actions
1038 lines (989 loc) · 59.2 KB
/
testing.html
File metadata and controls
1038 lines (989 loc) · 59.2 KB
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 dir="ltr" lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Getting Started with Testing in Rails — Ruby on Rails Guides</title>
<link rel="stylesheet" type="text/css" href="stylesheets/style.css" data-turbo-track="reload">
<link rel="stylesheet" type="text/css" href="stylesheets/print.css" media="print">
<link rel="stylesheet" type="text/css" href="stylesheets/highlight.css" data-turbo-track="reload">
<link rel="icon" href="images/backend-development.svg" sizes="any">
<script src="javascripts/@hotwired--turbo.js" data-turbo-track="reload"></script>
<script src="javascripts/clipboard.js" data-turbo-track="reload"></script>
<script src="javascripts/guides.js" data-turbo-track="reload"></script>
<meta property="og:title" content="Getting Started with Testing in Rails — Ruby on Rails Guides" />
<meta name="description" content="Getting Started with Testing in RailsThis guide gives an introduction to built-in mechanisms in Rails for testing your application.After reading this guide, you will know: Rails testing terminology. How to write unit tests for your applications models and controllers How to write system tests for your application. This guide is a shorter version of the offical Guide to Testing Rails Applications.Fork the example app 'testing for stars' and try out what you learn here." />
<meta property="og:description" content="Getting Started with Testing in RailsThis guide gives an introduction to built-in mechanisms in Rails for testing your application.After reading this guide, you will know: Rails testing terminology. How to write unit tests for your applications models and controllers How to write system tests for your application. This guide is a shorter version of the offical Guide to Testing Rails Applications.Fork the example app 'testing for stars' and try out what you learn here." />
<meta property="og:locale" content="en_US" />
<meta property="og:site_name" content="Textbook Backend Developemnt" />
<meta property="og:image" content="images/backend-development.svg" />
<meta property="og:type" content="website" />
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Noto+Sans+Arabic:wght@100..900&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=Heebo:wght@100..900&family=Noto+Sans+Arabic:wght@100..900&display=swap" rel="stylesheet">
<meta name="theme-color" content="#2e56e9">
</head>
<body class="guide">
<header id="page_header">
<div class="wrapper clearfix">
<nav id="feature_nav">
<div class="header-logo">
<a href="/">Backend Development</a>
</div>
<ul class="nav">
<li><a class="nav-item" id="home_nav" href="/">Home</a></li>
<li class="guides-index guides-index-large">
<a href="index.html" id="guidesMenu" class="guides-index-item nav-item">Index</a>
<div id="guides" class="clearfix" style="display: none;">
<hr />
<dl class="guides-section-container">
<div class="guides-section">
<dt>Ruby on Rails</dt>
<dd><a href="ruby_commandline.html">Ruby Commandline</a></dd>
<dd><a href="rails_database_and_model.html">Models and ActiveRecord</a></dd>
<dd><a href="rails_db.html">Database and Migrations</a></dd>
<dd><a href="rails_associations_and_validations.html">Associations and Validations</a></dd>
<dd><a href="rails_view_and_controller.html">Routing, View and Controller</a></dd>
<dd><a href="rails_authentication.html">Simple Authentication</a></dd>
<dd><a href="assets_and_import_map.html">The Asset Pipeline and Importmaps</a></dd>
<dd><a href="testing.html">Getting started with Testing</a></dd>
<dd><a href="refactoring_rails.html">Refactoring Rails</a></dd>
<dd><a href="deploy-to-paas.html">Deploy to PAAS</a></dd>
<dd><a href="rails_gems.html">Ruby Gems for your Rails Project</a></dd>
<dd><a href="deploying_rails.html">Deploying Rails</a></dd>
</div>
<div class="guides-section">
<dt>Ruby on Rails - Advanced Topics</dt>
<dd><a href="deploy-to-paas.html">Deploy to PAAS</a></dd>
<dd><a href="rest-api.html">REST API</a></dd>
<dd><a href="graphql-api.html">GraphQL API</a></dd>
<dd><a href="rails_websockets.html">Websocket in Rails</a></dd>
<dd><a href="jobs_and_tasks.html">Jobs and Tasks in Rails</a></dd>
<dd><a href="rails_security.html">Rails Security</a></dd>
</div>
<div class="guides-section">
<dt>Overarching Concerns</dt>
<dd><a href="issue.html">Issue Lifecycle</a></dd>
<dd><a href="security.html">Security</a></dd>
<dd><a href="adv_authentication.html">Advanced Authentication</a></dd>
<dd><a href="caching.html">Caching</a></dd>
<dd><a href="advanced_testing.html">Advanced Testing</a></dd>
<dd><a href="internationalization.html">Internationalization (I18n)</a></dd>
<dd><a href="git_rebasing.html">Git Rebasing</a></dd>
</div>
<div class="guides-section">
<dt>Nodes.js</dt>
<dd><a href="node_vs_rails.html">Node vs. Rails</a></dd>
<dd><a href="node_basics.html">Node Basics</a></dd>
<dd><a href="node_websockets.html">Node Websockets</a></dd>
<dd><a href="node_express.html">Node Web App</a></dd>
<dd><a href="node_cluster.html">Scaling Node</a></dd>
</div>
<div class="guides-section">
<dt>Next.js</dt>
<dd><a href="nextjs.html">Next.js</a></dd>
</div>
</dl>
</div>
</li>
<li class="guides-index guides-index-small">
<select class="guides-index-item nav-item">
<option value="index.html">Index</option>
<optgroup label="Ruby on Rails">
<option value="ruby_commandline.html">Ruby Commandline</option>
<option value="rails_database_and_model.html">Models and ActiveRecord</option>
<option value="rails_db.html">Database and Migrations</option>
<option value="rails_associations_and_validations.html">Associations and Validations</option>
<option value="rails_view_and_controller.html">Routing, View and Controller</option>
<option value="rails_authentication.html">Simple Authentication</option>
<option value="assets_and_import_map.html">The Asset Pipeline and Importmaps</option>
<option value="testing.html">Getting started with Testing</option>
<option value="refactoring_rails.html">Refactoring Rails</option>
<option value="deploy-to-paas.html">Deploy to PAAS</option>
<option value="rails_gems.html">Ruby Gems for your Rails Project</option>
<option value="deploying_rails.html">Deploying Rails</option>
</optgroup>
<optgroup label="Ruby on Rails - Advanced Topics">
<option value="deploy-to-paas.html">Deploy to PAAS</option>
<option value="rest-api.html">REST API</option>
<option value="graphql-api.html">GraphQL API</option>
<option value="rails_websockets.html">Websocket in Rails</option>
<option value="jobs_and_tasks.html">Jobs and Tasks in Rails</option>
<option value="rails_security.html">Rails Security</option>
</optgroup>
<optgroup label="Overarching Concerns">
<option value="issue.html">Issue Lifecycle</option>
<option value="security.html">Security</option>
<option value="adv_authentication.html">Advanced Authentication</option>
<option value="caching.html">Caching</option>
<option value="advanced_testing.html">Advanced Testing</option>
<option value="internationalization.html">Internationalization (I18n)</option>
<option value="git_rebasing.html">Git Rebasing</option>
</optgroup>
<optgroup label="Nodes.js">
<option value="node_vs_rails.html">Node vs. Rails</option>
<option value="node_basics.html">Node Basics</option>
<option value="node_websockets.html">Node Websockets</option>
<option value="node_express.html">Node Web App</option>
<option value="node_cluster.html">Scaling Node</option>
</optgroup>
<optgroup label="Next.js">
<option value="nextjs.html">Next.js</option>
</optgroup>
</select>
</li>
</ul>
</nav>
</div>
</header>
<hr class="hide" />
<section id="feature">
<div class="wrapper">
<h1>Getting Started with Testing in Rails</h1><p>This guide gives an introduction
to 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 tests for your applications models and controllers</li>
<li>How to write system tests for your application.</li>
</ul>
<p>This guide is a shorter version of the offical
<a href="https://guides.rubyonrails.org/testing.html">Guide to Testing Rails Applications</a>.</p><div class="interstitial repo"><p>Fork the <a href="https://github.com/backend-development/rails-example-testing-for-stars">example app 'testing for stars'</a> and try out what you learn here.</p></div>
<nav id="subCol">
<h3 class="chapter">
<picture>
<!-- Using the `source` HTML tag to set the dark theme image -->
<source
srcset="images/icon_book-close-bookmark-1-wht.svg"
media="(prefers-color-scheme: dark)"
/>
<img src="images/icon_book-close-bookmark-1.svg" alt="Chapter Icon" />
</picture>
Chapters
</h3>
<ol class="chapters">
<li><a href="#why-write-tests-questionmark">Why Write Tests?</a></li>
<li><a href="#setup">Setup</a>
<ul>
<li><a href="#folders-and-files">Folders and Files</a></li>
<li><a href="#the-test-environment">The Test Environment</a></li>
<li><a href="#write-one-test">Write one Test</a></li>
</ul></li>
<li><a href="#test-driven-development">Test Driven Development</a>
<ul>
<li><a href="#red">Red</a></li>
<li><a href="#green">Green</a></li>
</ul></li>
<li><a href="#unit-tests">Unit Tests</a>
<ul>
<li><a href="#what-an-error-in-you-test-looks-like">What an error in you test looks like</a></li>
<li><a href="#available-assertions">Available Assertions</a></li>
<li><a href="#better-asserstion">Better Asserstion</a></li>
<li><a href="#testing-a-model">Testing a Model</a></li>
<li><a href="#testing-a-controller">Testing a Controller</a></li>
</ul></li>
<li><a href="#test-data">Test Data</a>
<ul>
<li><a href="#maintaining-the-test-database-schema">Maintaining the test database schema</a></li>
<li><a href="#test-data-with-fixtures">Test Data with Fixtures</a></li>
</ul></li>
<li><a href="#system-tests">System Tests</a>
<ul>
<li><a href="#some-helper-methods">Some helper methods</a></li>
<li><a href="#some-assertions">Some assertions</a></li>
<li><a href="#debugging">debugging</a></li>
<li><a href="#testing-javascript">Testing Javascript</a></li>
</ul></li>
<li><a href="#further-reading">Further Reading</a></li>
</ol>
</nav>
<hr>
</div>
</section>
<main id="container">
<div class="wrapper">
<div id="mainCol">
<div class='slide'>
</div>
<div class='slide'>
<p class='slide_break_block'><a class='slide_break' id='slide-0' href='slides_testing.html#/0'>◻</a></p>
<h2 id="why-write-tests-questionmark"><a class="anchorlink" href="#why-write-tests-questionmark"><span>1</span> Why Write Tests?</a></h2><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 after every change in the code you can ensure that you did not break anything.</p><p>Rails tests can also simulate browser requests without or with javascript and thus you can test your application's response without having to test it through your browser.</p></div>
<div class='slide'>
<p class='slide_break_block'><a class='slide_break' id='slide-1' href='slides_testing.html#/1'>◻</a></p>
<h2 id="setup"><a class="anchorlink" href="#setup"><span>2</span> Setup</a></h2></div>
<div class='slide'>
<p class='slide_break_block'><a class='slide_break' id='slide-2' href='slides_testing.html#/2'>◻</a></p>
<h3 id="folders-and-files"><a class="anchorlink" href="#folders-and-files"><span>2.1</span> Folders and Files</a></h3><p>Rails creates a <code>test</code> directory for you. If you list the contents of this directory you will
find two files that hold the configuration for your tests:</p>
<ul>
<li><code>test_helper.rb</code> global test configuration</li>
<li><code>application_system_test_case.rb</code> configure a browser for system test</li>
</ul>
<p>and several directories:</p><p>The <code>models</code>, <code>controllers</code>, <code>mailers</code>, <code>channels</code>, and <code>helpers</code> directory
hold tests for (surprise) models, controllers, mailers, channels and view helpers respectively.
These tests that are focussed on one single class are also called <em>unit tests</em>.</p><p>The <code>integration</code> directory hold tests that exercise the whole Rails stack,
from HTTP Request through routes, controllers, down to models and back
up to the view. The only thing left out is the client side of your app: Javascript
cannot be tested here.</p><p>The <code>system</code> directory is meant to hold tests that test the
whole system by accessing the app with a browser, including running
the javascript.</p><p>Fixtures are a way of organizing test data; they reside in the <code>fixtures</code> directory.</p></div>
<div class='slide'>
<p class='slide_break_block'><a class='slide_break' id='slide-3' href='slides_testing.html#/3'>◻</a></p>
<h3 id="the-test-environment"><a class="anchorlink" href="#the-test-environment"><span>2.2</span> The Test Environment</a></h3><p>By default, every Rails application has three environments: development, test, and production.</p><p>Each environment has a configuration file in <code>config/environments/</code>.
For the test environment the file is <code>config/environments/test.rb</code>.</p><p>In the Gemfile you can add gems that are only used in one environment
by putting them in a section like so:</p><div class="interstitial code">
<pre><code class="highlight plaintext"># Gemfile
# use gem capybara only in test environment:
group :test do
gem 'capybara', '~> 2.13'
end
</code></pre>
<button class="clipboard-button" data-clipboard-text="# Gemfile
# use gem capybara only in test environment:
group :test do
gem 'capybara', '~> 2.13'
end
">Copy</button>
</div>
</div>
<div class='slide'>
<p class='slide_break_block'><a class='slide_break' id='slide-4' href='slides_testing.html#/4'>◻</a></p>
<h3 id="write-one-test"><a class="anchorlink" href="#write-one-test"><span>2.3</span> Write one Test</a></h3><p>When you use a generator it will also create
basic tests and fixtures for you:</p><div class="interstitial code">
<pre><code class="highlight console"><span class="gp">$</span><span class="w"> </span><span class="nb">bin/rails </span>generate model article title:string body:text
<span class="c">...
</span><span class="go">create app/models/article.rb
create test/models/article_test.rb
create test/fixtures/articles.yml
</span><span class="c">...
</span></code></pre>
<button class="clipboard-button" data-clipboard-text="bin/rails generate model article title:string body:text
">Copy</button>
</div>
</div>
<div class='slide'>
<p class='slide_break_block'><a class='slide_break' id='slide-5' href='slides_testing.html#/5'>◻</a></p>
The default test stub in <code>test/models/article_test.rb</code> looks like this:</p><div class="interstitial code">
<pre><code class="highlight ruby"><span class="nb">require</span> <span class="s1">'test_helper'</span>
<span class="k">class</span> <span class="nc">ArticleTest</span> <span class="o"><</span> <span class="no">ActiveSupport</span><span class="o">::</span><span class="no">TestCase</span>
<span class="c1"># test "the truth" do</span>
<span class="c1"># assert true</span>
<span class="c1"># end</span>
<span class="k">end</span>
</code></pre>
<button class="clipboard-button" data-clipboard-text="require 'test_helper'
class ArticleTest < ActiveSupport::TestCase
# test "the truth" do
# assert true
# end
end
">Copy</button>
</div>
<p>A line by line examination of this file will help get you oriented to Rails testing code and terminology.</p></div>
<div class='slide'>
<p class='slide_break_block'><a class='slide_break' id='slide-6' href='slides_testing.html#/6'>◻</a></p>
<div class="interstitial code">
<pre><code class="highlight ruby"><span class="nb">require</span> <span class="s1">'test_helper'</span>
</code></pre>
<button class="clipboard-button" data-clipboard-text="require 'test_helper'
">Copy</button>
</div>
<p>By requiring the file <code>test_helper.rb</code> the default configuration to run our tests is loaded. You will include this with all the tests you write.</p></div>
<div class='slide'>
<p class='slide_break_block'><a class='slide_break' id='slide-7' href='slides_testing.html#/7'>◻</a></p>
<div class="interstitial code">
<pre><code class="highlight ruby"><span class="k">class</span> <span class="nc">ArticleTest</span> <span class="o"><</span> <span class="no">ActiveSupport</span><span class="o">::</span><span class="no">TestCase</span>
</code></pre>
<button class="clipboard-button" data-clipboard-text="class ArticleTest < ActiveSupport::TestCase
">Copy</button>
</div>
<p>The <code>ArticleTest</code> class defines a <em>test case</em> because it inherits from <code>ActiveSupport::TestCase</code>, which
in turn inherits from <code>Minitest::Test</code>.</p></div>
<div class='slide'>
<p class='slide_break_block'><a class='slide_break' id='slide-8' href='slides_testing.html#/8'>◻</a></p>
<p>Inside this class you will define the tests, either by
giving them a method name beginning with <code>test_</code> (case sensitive) or
by using this syntax:</p><div class="interstitial code">
<pre><code class="highlight ruby"><span class="nb">test</span> <span class="s2">"the truth"</span> <span class="k">do</span>
<span class="n">assert</span> <span class="kp">true</span>
<span class="k">end</span>
</code></pre>
<button class="clipboard-button" data-clipboard-text="test "the truth" do
assert true
end
">Copy</button>
</div>
<p>Which is approximately the same as writing this:</p><div class="interstitial code">
<pre><code class="highlight ruby"><span class="k">def</span> <span class="nf">test_the_truth</span>
<span class="n">assert</span> <span class="kp">true</span>
<span class="k">end</span>
</code></pre>
<button class="clipboard-button" data-clipboard-text="def test_the_truth
assert true
end
">Copy</button>
</div>
</div>
<div class='slide'>
<p class='slide_break_block'><a class='slide_break' id='slide-9' href='slides_testing.html#/9'>◻</a></p>
<p>Next, let's look at our first assertion:</p><div class="interstitial code">
<pre><code class="highlight ruby"><span class="n">assert</span> <span class="kp">true</span>
</code></pre>
<button class="clipboard-button" data-clipboard-text="assert true
">Copy</button>
</div>
<p>An assertion is a line of code that evaluates an expression for expected results.
<code>assert true</code> is always satisfied, so this test always passes.</p></div>
<div class='slide'>
<p class='slide_break_block'><a class='slide_break' id='slide-10' href='slides_testing.html#/10'>◻</a></p>
<p>In a real test an assertion can check many things:</p>
<ul>
<li>does this value equal that value?</li>
<li>is this value nil?</li>
<li>does this line of code throw an exception?</li>
<li>is the user's password longer than 5 characters?</li>
</ul>
</div>
<div class='slide'>
<p class='slide_break_block'><a class='slide_break' id='slide-11' href='slides_testing.html#/11'>◻</a></p>
<p>Every test must contain at least one assertion, with no restriction as to how many assertions are allowed. Only when all the assertions are successful will the test pass.</p></div>
<div class='slide'>
<p class='slide_break_block'><a class='slide_break' id='slide-12' href='slides_testing.html#/12'>◻</a></p>
<h2 id="test-driven-development"><a class="anchorlink" href="#test-driven-development"><span>3</span> Test Driven Development</a></h2><p>Here an example of a useful test, written with
<a href="http://c2.com/cgi/wiki?TestDrivenDevelopment"><em>Test-Driven Development</em> (TDD)</a>.</p><p>Test Driven Development means:</p>
<ol>
<li>Write a test - it fails - "RED"</li>
<li>Write some code to make the test pass - "GREEN"</li>
<li>Improve your code, but make sure the test still passes - "REFACTOR"</li>
</ol>
<p>For this example I want to add a validation
to my article class to forbid very short or missing titles.</p></div>
<div class='slide'>
<p class='slide_break_block'><a class='slide_break' id='slide-13' href='slides_testing.html#/13'>◻</a></p>
<h3 id="red"><a class="anchorlink" href="#red"><span>3.1</span> Red</a></h3><p>I start by writing this test:</p><div class="interstitial code">
<pre><code class="highlight ruby"><span class="nb">test</span> <span class="s2">"article title needs to be at least 3 characters long"</span> <span class="k">do</span>
<span class="n">a</span> <span class="o">=</span> <span class="no">Article</span><span class="p">.</span><span class="nf">new</span><span class="p">(</span><span class="ss">title: </span><span class="s1">'x'</span><span class="p">)</span>
<span class="n">assert_not</span> <span class="n">article</span><span class="p">.</span><span class="nf">save</span>
<span class="k">end</span>
</code></pre>
<button class="clipboard-button" data-clipboard-text="test "article title needs to be at least 3 characters long" do
a = Article.new(title: 'x')
assert_not article.save
end
">Copy</button>
</div>
</div>
<div class='slide'>
<p class='slide_break_block'><a class='slide_break' id='slide-14' href='slides_testing.html#/14'>◻</a></p>
<p>To run all the tests for your project use <code>rails test</code>.</p></div>
<div class='slide'>
<p class='slide_break_block'><a class='slide_break' id='slide-15' href='slides_testing.html#/15'>◻</a></p>
<p>If you run the test above the result might look like this:</p><div class="interstitial code">
<pre><code class="highlight console"><span class="gp">$</span><span class="w"> </span><span class="nb">rails test</span>
<span class="go">Run options: --seed 33837
</span><span class="gp">#</span><span class="w"> </span>Running:
<span class="go">
........F
Finished in 0.492655s, 18.2684 runs/s, 30.4473 assertions/s.
1) Failure:
</span><span class="gp">ArticleTest#</span>article_should_not_save_article_without_title <span class="o">[</span><span class="nb">test</span>/models/article_test.rb:10]:
<span class="go">Expected true to be nil or false
9 runs, 15 assertions, 1 failures, 0 errors, 0 skips
</span></code></pre>
<button class="clipboard-button" data-clipboard-text="rails test
">Copy</button>
</div>
<p>In the output, <code>F</code> denotes a failure. You can see the corresponding trace shown under <code>1)</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.</p></div>
<div class='slide'>
<p class='slide_break_block'><a class='slide_break' id='slide-16' href='slides_testing.html#/16'>◻</a></p>
<h3 id="green"><a class="anchorlink" href="#green"><span>3.2</span> Green</a></h3><p>Now to get this test to pass we can add a model level validation for the <em>title</em> field.</p><div class="interstitial code">
<pre><code class="highlight ruby"><span class="k">class</span> <span class="nc">Article</span> <span class="o"><</span> <span class="no">ApplicationRecord</span>
<span class="n">validates</span> <span class="ss">:title</span><span class="p">,</span> <span class="ss">length: </span><span class="p">{</span> <span class="ss">minimum: </span><span class="mi">3</span> <span class="p">}</span>
<span class="k">end</span>
</code></pre>
<button class="clipboard-button" data-clipboard-text="class Article < ApplicationRecord
validates :title, length: { minimum: 3 }
end
">Copy</button>
</div>
<p>Now the test should pass. Verify this by actually running the test!</p><div class="interstitial code">
<pre><code class="highlight console"><span class="gp">$</span><span class="w"> </span><span class="nb">rails test</span>
<span class="go">Run options: --seed 8625
</span><span class="gp">#</span><span class="w"> </span>Running:
<span class="go">
</span><span class="c">........
</span><span class="go">
Finished in 0.498780s, 16.0391 runs/s, 28.0685 assertions/s.
8 runs, 14 assertions, 0 failures, 0 errors, 0 skips
</span></code></pre>
<button class="clipboard-button" data-clipboard-text="rails test
">Copy</button>
</div>
<p>Every dot stands for one test that ran through sucessfully.</p></div>
<div class='slide'>
<p class='slide_break_block'><a class='slide_break' id='slide-17' href='slides_testing.html#/17'>◻</a></p>
<h2 id="unit-tests"><a class="anchorlink" href="#unit-tests"><span>4</span> Unit Tests</a></h2></div>
<div class='slide'>
<p class='slide_break_block'><a class='slide_break' id='slide-18' href='slides_testing.html#/18'>◻</a></p>
<h3 id="what-an-error-in-you-test-looks-like"><a class="anchorlink" href="#what-an-error-in-you-test-looks-like"><span>4.1</span> What an error in you test looks like</a></h3><p>An error is different from a failing test. An error
is a problem in your test code, not your application code.
To see how an error gets reported, here's a test containing an error:</p><div class="interstitial code">
<pre><code class="highlight ruby"><span class="nb">test</span> <span class="s2">"should report error"</span> <span class="k">do</span>
<span class="c1"># some_undefined_variable is not defined elsewhere in the test case</span>
<span class="n">some_undefined_variable</span>
<span class="n">assert</span> <span class="kp">true</span>
<span class="k">end</span>
</code></pre>
<button class="clipboard-button" data-clipboard-text="test "should report error" do
# some_undefined_variable is not defined elsewhere in the test case
some_undefined_variable
assert true
end
">Copy</button>
</div>
<p>Now you can see even more output in the console from running the tests:</p><div class="interstitial code">
<pre><code class="highlight console"><span class="gp">$</span><span class="w"> </span><span class="nb">rails test</span>
<span class="go">.....E...
Finished tests in 0.030974s, 32.2851 tests/s, 0.0000 assertions/s.
1) Error:
test_should_report_error(ArticleTest):
</span><span class="gp">NameError: undefined local variable or method `some_undefined_variable' for #</span><ArticleTest:0x007fe32e24afe0>
<span class="gp"> test/models/article_test.rb:10:in `block in <class:ArticleTest></span><span class="s1">'
</span><span class="go">
10 tests, 10 assertions, 0 failures, 1 errors, 0 skips
</span></code></pre>
<button class="clipboard-button" data-clipboard-text="rails test
">Copy</button>
</div>
<p>Notice the 'E' in the output. It denotes a test with an error.</p><div class="interstitial note"><p>The execution of each test method stops as soon as any error or an
assertion failure is encountered. But the test suite continues with the next
test. All test methods are executed in random 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. Read the backtrace!</p></div>
<div class='slide'>
<p class='slide_break_block'><a class='slide_break' id='slide-19' href='slides_testing.html#/19'>◻</a></p>
<h4 id="how-to-catch-exceptions-from-your-application-code"><a class="anchorlink" href="#how-to-catch-exceptions-from-your-application-code"><span>4.1.1</span> How to catch exceptions from your application code</a></h4><p>If you want to ensure that an exception is raised
by your application code
you can use <code>assert_raises</code> like so:</p><div class="interstitial code">
<pre><code class="highlight ruby"><span class="nb">test</span> <span class="s2">"MyClass no longer implements @@counter, raises error"</span> <span class="k">do</span>
<span class="n">assert_raises</span><span class="p">(</span><span class="no">NameError</span><span class="p">)</span> <span class="k">do</span>
<span class="no">MyClass</span><span class="p">.</span><span class="nf">counter</span>
<span class="k">end</span>
<span class="k">end</span>
</code></pre>
<button class="clipboard-button" data-clipboard-text="test "MyClass no longer implements @@counter, raises error" do
assert_raises(NameError) do
MyClass.counter
end
end
">Copy</button>
</div>
</div>
<div class='slide'>
<p class='slide_break_block'><a class='slide_break' id='slide-20' href='slides_testing.html#/20'>◻</a></p>
<h3 id="available-assertions"><a class="anchorlink" href="#available-assertions"><span>4.2</span> Available Assertions</a></h3><p>You have seen some assertions above.</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 that is only
displayed if the test fails. It is available in all assertions, but only shown in
the first one here. For most assertions there is a simple negation <code>assert</code> and <code>assert_not</code>, <code>assert_equal</code> and
<code>assert_no_equal</code>, and so on.</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 )</code></td>
<td>Ensures that <code>test</code> is false.</td>
</tr>
<tr>
<td><code>assert_equal( expected, actual )</code></td>
<td>Ensures that <code>expected == actual</code> is true.</td>
</tr>
<tr>
<td><code>assert_same( expected, actual )</code></td>
<td>Ensures that expected and actual are the exact same object.</td>
</tr>
<tr>
<td><code>assert_nil( obj )</code></td>
<td>Ensures that <code>obj.nil?</code> is true.</td>
</tr>
<tr>
<td><code>assert_empty( obj )</code></td>
<td>Ensures that <code>obj</code> is <code>empty?</code>.</td>
</tr>
<tr>
<td><code>assert_match( regexp, string )</code></td>
<td>Ensures that a string matches the regular expression.</td>
</tr>
<tr>
<td><code>assert_no_match( regexp, string )</code></td>
<td>Ensures that a string doesn't match the regular expression.</td>
</tr>
<tr>
<td><code>assert_includes( collection, obj )</code></td>
<td>Ensures that <code>obj</code> is in <code>collection</code>.</td>
</tr>
<tr>
<td><code>assert_in_delta(expectated,actual,delta)</code></td>
<td>Ensures that the numbers <code>expectated</code> and <code>actual</code> are within <code>+/-delta</code> of each other.</td>
</tr>
<tr>
<td><code>assert_raises( exception ){ block }</code></td>
<td>Ensures that the given block raises the given exception.</td>
</tr>
<tr>
<td><code>assert_instance_of( class, obj )</code></td>
<td>Ensures that <code>obj</code> is an instance of <code>class</code>.</td>
</tr>
<tr>
<td><code>assert_kind_of( class, obj )</code></td>
<td>Ensures that <code>obj</code> is an instance of <code>class</code> or is descended from it.</td>
</tr>
<tr>
<td><code>assert_respond_to( obj, symbol )</code></td>
<td>Ensures that <code>obj</code> responds to <code>symbol</code>, for example because it implements a method by that name or inherits one.</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="https://github.com/seattlerb/minitest#user-content-description">Minitest API documentation</a>, specifically
<a href="https://docs.ruby-lang.org/en/2.1.0/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>
<div class='slide'>
<p class='slide_break_block'><a class='slide_break' id='slide-21' href='slides_testing.html#/21'>◻</a></p>
<h3 id="better-asserstion"><a class="anchorlink" href="#better-asserstion"><span>4.3</span> Better Asserstion</a></h3><p><a href="https://github.com/hamcrest/ramcrest">better assertion with ramcrest</a></p></div>
<div class='slide'>
<p class='slide_break_block'><a class='slide_break' id='slide-22' href='slides_testing.html#/22'>◻</a></p>
<h3 id="testing-a-model"><a class="anchorlink" href="#testing-a-model"><span>4.4</span> Testing a Model</a></h3><p>Models are easy to test separately because they do not depend on
other code (most of the time). In Rails the tests for a model X
are found in <code>test/models/x_test.rb</code>.</p><p>All the examples shown so far are from model tests.
Below you can see what the a complete model test could look like.
There is a <code>setup</code> section that will be executed before
each test.</p><div class="interstitial code">
<pre><code class="highlight ruby"><span class="c1"># file test/models/course_test.rb</span>
<span class="nb">require</span> <span class="s1">'test_helper'</span>
<span class="k">class</span> <span class="nc">CourseTest</span> <span class="o"><</span> <span class="no">ActiveSupport</span><span class="o">::</span><span class="no">TestCase</span>
<span class="n">setup</span> <span class="k">do</span>
<span class="vi">@course</span> <span class="o">=</span> <span class="n">courses</span><span class="p">(</span><span class="ss">:one</span><span class="p">)</span>
<span class="k">end</span>
<span class="nb">test</span> <span class="s2">"should not save new course without title"</span> <span class="k">do</span>
<span class="n">course</span> <span class="o">=</span> <span class="no">Course</span><span class="p">.</span><span class="nf">new</span>
<span class="n">assert_not</span> <span class="n">course</span><span class="p">.</span><span class="nf">save</span><span class="p">,</span> <span class="s2">"Saved new course without a title"</span>
<span class="k">end</span>
<span class="nb">test</span> <span class="s2">"cannot save existing course after removing title"</span> <span class="k">do</span>
<span class="vi">@course</span><span class="p">.</span><span class="nf">title</span> <span class="o">=</span> <span class="s1">''</span>
<span class="n">assert_not</span> <span class="vi">@course</span><span class="p">.</span><span class="nf">save</span><span class="p">,</span> <span class="s2">"Saved existing course without a title"</span>
<span class="k">end</span>
<span class="nb">test</span> <span class="s2">"Course no longer implements .counter, raises error"</span> <span class="k">do</span>
<span class="n">assert_raises</span><span class="p">(</span><span class="no">NameError</span><span class="p">)</span> <span class="k">do</span>
<span class="vi">@course</span><span class="p">.</span><span class="nf">counter</span>
<span class="k">end</span>
<span class="k">end</span>
<span class="k">end</span>
</code></pre>
<button class="clipboard-button" data-clipboard-text="# file test/models/course_test.rb
require 'test_helper'
class CourseTest < ActiveSupport::TestCase
setup do
@course = courses(:one)
end
test "should not save new course without title" do
course = Course.new
assert_not course.save, "Saved new course without a title"
end
test "cannot save existing course after removing title" do
@course.title = ''
assert_not @course.save, "Saved existing course without a title"
end
test "Course no longer implements .counter, raises error" do
assert_raises(NameError) do
@course.counter
end
end
end
">Copy</button>
</div>
<p>So is the model test a unit test? It only tests one unit
of source code that you have written. It also exercises ActiveRecord
and the test database. So you could argue that it is more
than just a unit test. But for now it is a near a unit test as
we can get. We will look at more <a href="advanced_testing.html">advanced testing</a>
later one. There you will learn how to build tests that only
test one unit of code.</p></div>
<div class='slide'>
<p class='slide_break_block'><a class='slide_break' id='slide-23' href='slides_testing.html#/23'>◻</a></p>
<h3 id="testing-a-controller"><a class="anchorlink" href="#testing-a-controller"><span>4.5</span> Testing a Controller</a></h3><p>Controller tests exercise several parts of the rails stack: routing, the controller, models, the test database. But they do try to keep
views out of the mix.</p><p>To activate controller test add to your Gemfile:</p><div class="interstitial code">
<pre><code class="highlight plaintext">group :development, :test do
gem 'rails-controller-testing'
end
</code></pre>
<button class="clipboard-button" data-clipboard-text="group :development, :test do
gem 'rails-controller-testing'
end
">Copy</button>
</div>
<p>Testing the controller <em>without</em> testing the view
at the same time is quite tricky. You should test for things such as:</p>
<ul>
<li>was the web request successful?</li>
<li>was the user redirected to the right page?</li>
<li>was the user successfully authenticated?</li>
<li>was the correct object sent to the view?</li>
</ul>
<p>In a controller test you can use the methods <code>get</code>, <code>post</code>, and so on.
These will be handled by rails routing as usual, and end up
calling an action in the controller with certain parameters.</p><p>In this example the <code>create</code> action of the article controller is called by
sending a post request to articles_url.
The params hash is set up with key <code>article[title]</code> and value <code>some title</code>:</p><div class="interstitial code">
<pre><code class="highlight plaintext">post articles_url, params: { article: { title: 'some title' } }
</code></pre>
<button class="clipboard-button" data-clipboard-text="post articles_url, params: { article: { title: 'some title' } }
">Copy</button>
</div>
<p>This example just shows <code>params</code>, you can also set:</p>
<ul>
<li><code>headers</code> a hash of HTTP Request headers</li>
<li><code>env</code> a hash of environment variables</li>
<li><code>xhr</code> true or false to make this an AJAX request or not</li>
<li><code>as</code> to request a content type, for example <code>as: :json</code></li>
<li><code>cookies</code> to set cookies included in the request</li>
</ul>
<p>After the request you get the response and three hashes:</p>
<ul>
<li><code>session</code></li>
<li><code>flash</code></li>
<li><code>cookies</code></li>
</ul>
<p>Rails adds some custom assertions for controllers.
You can see them at work in the tests created by scaffold:</p><p><code>assert_response</code> checks the status code of the HTTP response generated
by the controller:</p><div class="interstitial code">
<pre><code class="highlight plaintext"># test/controller/articles_controller_test.rb
test "should get new" do
get :new
assert_response :success
end
</code></pre>
<button class="clipboard-button" data-clipboard-text="# test/controller/articles_controller_test.rb
test "should get new" do
get :new
assert_response :success
end
">Copy</button>
</div>
<p><code>assert_difference</code> checks a value before and after
a block of code is run, to make sure that the value changed
by one. This is often used when creating models:</p><div class="interstitial code">
<pre><code class="highlight plaintext">test "should create article" do
assert_difference('Article.count') do
post :create, params: { article: { title: 'some title' } }
end
end
</code></pre>
<button class="clipboard-button" data-clipboard-text="test "should create article" do
assert_difference('Article.count') do
post :create, params: { article: { title: 'some title' } }
end
end
">Copy</button>
</div>
<p><code>assert_redirect</code> makes sure the controller returns
a HTTP redirect header to the appropriate url:</p><div class="interstitial code">
<pre><code class="highlight plaintext">test "should destroy article" do
assert_difference('Article.count', -1) do
delete :destroy, params: { id: 1 }
end
assert_redirected_to articles_path
end
</code></pre>
<button class="clipboard-button" data-clipboard-text="test "should destroy article" do
assert_difference('Article.count', -1) do
delete :destroy, params: { id: 1 }
end
assert_redirected_to articles_path
end
">Copy</button>
</div>
</div>
<div class='slide'>
<p class='slide_break_block'><a class='slide_break' id='slide-24' href='slides_testing.html#/24'>◻</a></p>
<h2 id="test-data"><a class="anchorlink" href="#test-data"><span>5</span> Test Data</a></h2><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>The database for each environment 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></div>
<div class='slide'>
<p class='slide_break_block'><a class='slide_break' id='slide-25' href='slides_testing.html#/25'>◻</a></p>
<h3 id="maintaining-the-test-database-schema"><a class="anchorlink" href="#maintaining-the-test-database-schema"><span>5.1</span> Maintaining the test database schema</a></h3><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. If so, it will try to load <code>db/schema.rb</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="interstitial note"><p>If existing migrations required modifications, the test database needs to
be rebuilt. This can be done by executing <code>rails db:test:prepare</code>.</p></div></div>
<div class='slide'>
<p class='slide_break_block'><a class='slide_break' id='slide-26' href='slides_testing.html#/26'>◻</a></p>
<h3 id="test-data-with-fixtures"><a class="anchorlink" href="#test-data-with-fixtures"><span>5.2</span> Test Data with Fixtures</a></h3><p>For good tests, you'll need to give some thought to setting up test data.
In Rails, the most simple way of doing this is by defining and customizing fixtures.
Fixtures are database independent and written in YAML. There is one file per model.</p><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></div>
<div class='slide'>
<p class='slide_break_block'><a class='slide_break' id='slide-27' href='slides_testing.html#/27'>◻</a></p>
<h4 id="yaml"><a class="anchorlink" href="#yaml"><span>5.2.1</span> YAML</a></h4><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="interstitial code">
<pre><code class="highlight yaml"><span class="c1"># I am a YAML comment</span>
<span class="na">david</span><span class="pi">:</span>
<span class="na">name</span><span class="pi">:</span> <span class="s">David Heinemeier Hansson</span>
<span class="na">birthday</span><span class="pi">:</span> <span class="s">1979-10-15</span>
<span class="na">profession</span><span class="pi">:</span> <span class="s">systems development</span>
<span class="na">steve</span><span class="pi">:</span>
<span class="na">name</span><span class="pi">:</span> <span class="s">Steve Ross Kellock</span>
<span class="na">birthday</span><span class="pi">:</span> <span class="s">1974-09-27</span>
<span class="na">profession</span><span class="pi">:</span> <span class="s">guy with keyboard</span>
</code></pre>
<button class="clipboard-button" data-clipboard-text="# 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
">Copy</button>
</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 there are <a href="/rails_database_and_model.html#1-n-associations">associations</a>
between models, you can
simply refer to the fixture in a related model using its name.
Here's an example with a <code>belongs_to</code>/<code>has_many</code> association:</p><div class="interstitial code">
<pre><code class="highlight yaml"><span class="c1"># In fixtures/categories.yml</span>
<span class="na">about</span><span class="pi">:</span>
<span class="na">name</span><span class="pi">:</span> <span class="s">About This Site</span>
<span class="c1"># In fixtures/articles.yml</span>
<span class="na">one</span><span class="pi">:</span>
<span class="na">title</span><span class="pi">:</span> <span class="s">Welcome to Rails!</span>
<span class="na">body</span><span class="pi">:</span> <span class="s">Hello world!</span>
<span class="na">category</span><span class="pi">:</span> <span class="s">about</span>
</code></pre>
<button class="clipboard-button" data-clipboard-text="# In fixtures/categories.yml
about:
name: About This Site
# In fixtures/articles.yml
one:
title: Welcome to Rails!
body: Hello world!
category: about
">Copy</button>
</div>
<p>The <code>category</code> key of the <code>one</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="interstitial note"><p>Do not specify the <code>id:</code> attribute in 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://edgeapi.rubyonrails.org/classes/ActiveRecord/FixtureSet.html">Fixtures API documentation</a>.</p></div></div>
<div class='slide'>
<p class='slide_break_block'><a class='slide_break' id='slide-28' href='slides_testing.html#/28'>◻</a></p>
<h4 id="using-fixtures-in-tests"><a class="anchorlink" href="#using-fixtures-in-tests"><span>5.2.2</span> Using fixtures in Tests</a></h4><p>The data defined by the fixture files will be available
in your tests as Active Record objects. For example:</p><div class="interstitial code">
<pre><code class="highlight ruby"><span class="c1"># in test/models/user_test.rb</span>
<span class="c1"># the User object for the fixture named david</span>
<span class="n">users</span><span class="p">(</span><span class="ss">:david</span><span class="p">)</span>
<span class="c1"># turn the property for david called id</span>
<span class="n">users</span><span class="p">(</span><span class="ss">:david</span><span class="p">).</span><span class="nf">id</span>
<span class="c1"># one can access methods available on the User class</span>
<span class="n">users</span><span class="p">(</span><span class="ss">:david</span><span class="p">).</span><span class="nf">partner</span><span class="p">.</span><span class="nf">email</span>
</code></pre>
<button class="clipboard-button" data-clipboard-text="# in test/models/user_test.rb
# the User object for the fixture named david
users(:david)
# turn the property for david called id
users(:david).id
# one can access methods available on the User class
users(:david).partner.email
">Copy</button>
</div>
<p>To get multiple fixtures at once, you can pass in a list of fixture names. For example:</p><div class="interstitial code">
<pre><code class="highlight ruby"><span class="c1"># this will return an array containing the fixtures david and steve</span>
<span class="n">users</span><span class="p">(</span><span class="ss">:david</span><span class="p">,</span> <span class="ss">:steve</span><span class="p">)</span>
</code></pre>
<button class="clipboard-button" data-clipboard-text="# this will return an array containing the fixtures david and steve
users(:david, :steve)
">Copy</button>
</div>
</div>
<div class='slide'>
<p class='slide_break_block'><a class='slide_break' id='slide-29' href='slides_testing.html#/29'>◻</a></p>
<h2 id="system-tests"><a class="anchorlink" href="#system-tests"><span>6</span> System Tests</a></h2><p>System test are used to test that the various parts of your application interact correctly
to implement features. In a system test a real browser is used to test your app, including the client side javascript.</p><p>Rails comes with built in system tests. These are stored in the folder <code>test/system/</code></p><p>These tests take a lot more time to run than the unit test
discussed earlier. They are not included if you run <code>rails test</code>, you have
to start them separately with <code>rails test:system</code>.</p><p>We will use the gems <code>capybara</code> and <code>selenium-webdriver</code>. they will
enable us to sue headless browser firefox or chrome for system tests.</p><div class="interstitial code">
<pre><code class="highlight plaintext"># Gemfile
group :test do
gem 'capybara'
gem 'selenium-webdriver'
end
# test/application_system_test_case.rb
require 'test_helper'
class ApplicationSystemTestCase < ActionDispatch::SystemTestCase
driven_by :selenium, using: :headless_chrome, screen_size: [1400, 1400]
end
</code></pre>
<button class="clipboard-button" data-clipboard-text="# Gemfile
group :test do
gem 'capybara'
gem 'selenium-webdriver'
end
# test/application_system_test_case.rb
require 'test_helper'
class ApplicationSystemTestCase < ActionDispatch::SystemTestCase
driven_by :selenium, using: :headless_chrome, screen_size: [1400, 1400]
end
">Copy</button>
</div>
<p>There is a generator to create a test skeleton for you.</p><div class="interstitial code">
<pre><code class="highlight console"><span class="gp">$</span><span class="w"> </span><span class="nb">rails </span>generate test_unit:system add_a_star_to_a_user
<span class="go"> create test/system/add_a_star_to_a_user_test.rb
</span></code></pre>
<button class="clipboard-button" data-clipboard-text="rails generate test_unit:system add_a_star_to_a_user
">Copy</button>
</div>
<p>Here's what a freshly-generated system test looks like:</p><div class="interstitial code">
<pre><code class="highlight ruby"><span class="nb">require</span> <span class="s2">"application_system_test_case"</span>
<span class="k">class</span> <span class="nc">AddAStarToAUsersTest</span> <span class="o"><</span> <span class="no">ApplicationSystemTestCase</span>
<span class="c1"># test "visiting the index" do</span>
<span class="c1"># visit add_a_star_to_a_users_url</span>
<span class="c1">#</span>
<span class="c1"># assert_selector "h1", text: "AddAStarToAUser"</span>
<span class="c1"># end</span>
<span class="k">end</span>
</code></pre>
<button class="clipboard-button" data-clipboard-text="require "application_system_test_case"
class AddAStarToAUsersTest < ApplicationSystemTestCase
# test "visiting the index" do
# visit add_a_star_to_a_users_url
#
# assert_selector "h1", text: "AddAStarToAUser"
# end
end
">Copy</button>
</div>
<p><code>visit</code> is capybaras method for making a HTTP request just as the browser would.</p><p><code>assert_selector</code> is one of the assertions implemented by capybara. this
assertion will wait for the page to load, and then it will look
for a <code>h1</code> tag containing the text.</p><p>Generally speaking System tests are black box tests: we only interact with the
app through the web browser, and have no "inside knowledge" about the app.</p><p>In Rails system test you do have access to the full application including the database.</p></div>
<div class='slide'>
<p class='slide_break_block'><a class='slide_break' id='slide-30' href='slides_testing.html#/30'>◻</a></p>
<h3 id="some-helper-methods"><a class="anchorlink" href="#some-helper-methods"><span>6.1</span> Some helper methods</a></h3><div class="interstitial code">
<pre><code class="highlight plaintext">click_link('id-of-link')
click_link('Link Text')
find('#navigation').click_link('Home') # only look for link inside #navigation
click_button('Save')
find("#overlay").find_button('Send').click
fill_in('First Name', with: 'John') # fill in a text input field
choose('A Radio Button')
check('A Checkbox')
uncheck('A Checkbox')
select('Option', :from => 'Select Box')
attach_file('Image', Rails.root + 'test/fixtures/files/example.png') # file upload
all('a').each { |a| ... a[:href] ... } # loop over all the found nodes
within("li#employee") do # the code in the block will only use the dom inside li#employee
fill_in 'Name', :with => 'Jimmy'
...
end
page.execute_script 'window.scrollBy(0,10000)' # run javascript to simulate user behaviour
</code></pre>
<button class="clipboard-button" data-clipboard-text="click_link('id-of-link')
click_link('Link Text')
find('#navigation').click_link('Home') # only look for link inside #navigation
click_button('Save')
find("#overlay").find_button('Send').click
fill_in('First Name', with: 'John') # fill in a text input field
choose('A Radio Button')
check('A Checkbox')
uncheck('A Checkbox')
select('Option', :from => 'Select Box')
attach_file('Image', Rails.root + 'test/fixtures/files/example.png') # file upload
all('a').each { |a| ... a[:href] ... } # loop over all the found nodes
within("li#employee") do # the code in the block will only use the dom inside li#employee
fill_in 'Name', :with => 'Jimmy'
...
end
page.execute_script 'window.scrollBy(0,10000)' # run javascript to simulate user behaviour
">Copy</button>
</div>
</div>
<div class='slide'>
<p class='slide_break_block'><a class='slide_break' id='slide-31' href='slides_testing.html#/31'>◻</a></p>
<h3 id="some-assertions"><a class="anchorlink" href="#some-assertions"><span>6.2</span> Some assertions</a></h3><div class="interstitial code">
<pre><code class="highlight plaintext">assert_content('foo')
assert_text('bar')
assert_selector('table tr')
assert_button('save')
assert_checked_field('newsletter')
assert_link('more')
</code></pre>
<button class="clipboard-button" data-clipboard-text="assert_content('foo')
assert_text('bar')
assert_selector('table tr')
assert_button('save')
assert_checked_field('newsletter')
assert_link('more')
">Copy</button>
</div>
</div>
<div class='slide'>
<p class='slide_break_block'><a class='slide_break' id='slide-32' href='slides_testing.html#/32'>◻</a></p>
<h3 id="debugging"><a class="anchorlink" href="#debugging"><span>6.3</span> debugging</a></h3><p>As with all tests, you can read the log file <code>log/test.log</code> to see how you test is doing.</p><p>System tests offer two more options:</p><div class="interstitial code">
<pre><code class="highlight ruby"><span class="n">take_screenshot</span> <span class="c1"># and give it an automatic file name</span>
<span class="n">save_screenshot</span><span class="p">(</span><span class="s1">'tmp/screenshots/book_event_step1.png'</span><span class="p">)</span>
<span class="n">save_and_open_page</span>
</code></pre>
<button class="clipboard-button" data-clipboard-text="take_screenshot # and give it an automatic file name