-
Notifications
You must be signed in to change notification settings - Fork 0
/
testing.html
1388 lines (1259 loc) · 75.9 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="zh-TW">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>A Guide to Testing Rails Applications — Ruby on Rails 指南</title>
<meta name="description" content="Ruby on Rails 指南:系統學習 Rails(Rails 4.2 版本)" >
<meta name="keywords" content="Ruby on Rails Guides 指南 中文 學習 免費 網路 Web 開發" >
<meta name="author" content="http://git.io/G_R1sA">
<meta property="fb:admins" content="1340181291">
<meta property="og:title" content="A Guide to Testing Rails Applications — Ruby on Rails 指南" >
<meta property="og:site_name" content="Ruby on Rails 指南">
<meta property="og:image" content="http://rails.ruby.tw/images/rails_guides_cover.jpg">
<meta property="og:url" content="http://rails.ruby.tw/">
<meta property="og:type" content="article">
<meta property="og:description" content="Ruby on Rails 指南:系統學習 Rails(Rails 4.2 版本)">
<link rel="stylesheet" href="stylesheets/application.css">
<link href="http://fonts.googleapis.com/css?family=Noto+Sans:400,700|Noto+Serif:700|Source+Code+Pro" rel="stylesheet">
<link href="images/favicon.ico" rel="shortcut icon" type="image/x-icon">
</head>
<body class="guide">
<div id="fb-root"></div>
<script>(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/zh-TW/sdk.js#xfbml=1&appId=837401439623727&version=v2.0";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>
<script type="text/javascript">
window.twttr=(function(d,s,id){var t,js,fjs=d.getElementsByTagName(s)[0];if(d.getElementById(id)){return}js=d.createElement(s);js.id=id;js.src="https://platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);return window.twttr||(t={_e:[],ready:function(f){t._e.push(f)}})}(document,"script","twitter-wjs"));
</script>
<div id="topNav">
<div class="wrapper">
<strong class="more-info-label">更多內容 <a href="http://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="http://rubyonrails.org/">綜覽</a></li>
<li class="more-info"><a href="http://rubyonrails.org/download">下載</a></li>
<li class="more-info"><a href="http://rubyonrails.org/deploy">部署</a></li>
<li class="more-info"><a href="https://github.com/rails/rails">原始碼</a></li>
<li class="more-info"><a href="http://rubyonrails.org/screencasts">影片</a></li>
<li class="more-info"><a href="http://rubyonrails.org/documentation">文件</a></li>
<li class="more-info"><a href="http://rubyonrails.org/community">社群</a></li>
<li class="more-info"><a href="http://weblog.rubyonrails.org/">Blog</a></li>
</ul>
</div>
</div>
<div id="header">
<div class="wrapper clearfix">
<h1><a href="index.html" title="回首頁">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>
<dl class="L">
<dt>起步走</dt>
<dd><a href="getting_started.html">Rails 起步走</a></dd>
<dt>Models</dt>
<dd><a href="active_record_basics.html">Active Record 基礎</a></dd>
<dd><a href="active_record_migrations.html">Active Record 遷移</a></dd>
<dd><a href="active_record_validations.html">Active Record 驗證</a></dd>
<dd><a href="active_record_callbacks.html">Active Record 回呼</a></dd>
<dd><a href="association_basics.html">Active Record 關聯</a></dd>
<dd><a href="active_record_querying.html">Active Record 查詢</a></dd>
<dt>Views</dt>
<dd><a href="layouts_and_rendering.html">Rails 算繪與版型</a></dd>
<dd><a href="form_helpers.html">Action View 表單輔助方法</a></dd>
<dt>Controllers</dt>
<dd><a href="action_controller_overview.html">Action Controller 綜覽</a></dd>
<dd><a href="routing.html">Rails 路由:深入淺出</a></dd>
</dl>
<dl class="R">
<dt>深入了解</dt>
<dd><a href="active_support_core_extensions.html">Active Support 核心擴展</a></dd>
<dd><a href="i18n.html">Rails 國際化 API</a></dd>
<dd><a href="action_mailer_basics.html">Action Mailer 基礎</a></dd>
<dd><a href="active_job_basics.html">Active Job 基礎</a></dd>
<dd><a href="security.html">Rails 安全指南</a></dd>
<dd><a href="debugging_rails_applications.html">除錯 Rails 應用程式</a></dd>
<dd><a href="configuring.html">Rails 應用程式設定</a></dd>
<dd><a href="command_line.html">Rake 任務與 Rails 命令列工具</a></dd>
<dd><a href="asset_pipeline.html">Asset Pipeline</a></dd>
<dd><a href="working_with_javascript_in_rails.html">在 Rails 使用 JavaScript</a></dd>
<dd><a href="constant_autoloading_and_reloading.html">Constant Autoloading and Reloading</a></dd>
<dt>擴充 Rails</dt>
<dd><a href="rails_on_rack.html">Rails on Rack</a></dd>
<dd><a href="generators.html">客製與新建 Rails 產生器</a></dd>
<dd><a href="rails_application_templates.html">Rails 應用程式模版</a></dd>
<dt>貢獻 Ruby on Rails</dt>
<dd><a href="contributing_to_ruby_on_rails.html">貢獻 Ruby on Rails</a></dd>
<dd><a href="api_documentation_guidelines.html">API 文件準則</a></dd>
<dd><a href="ruby_on_rails_guides_guidelines.html">Ruby on Rails 指南準則</a></dd>
<dt>維護方針</dt>
<dd><a href="maintenance_policy.html">維護方針</a></dd>
<dt>發佈記</dt>
<dd><a href="upgrading_ruby_on_rails.html">升級 Ruby on Rails</a></dd>
<dd><a href="4_2_release_notes.html">Ruby on Rails 4.2 發佈記</a></dd>
<dd><a href="4_1_release_notes.html">Ruby on Rails 4.1 發佈記</a></dd>
<dd><a href="4_0_release_notes.html">Ruby on Rails 4.0 發佈記</a></dd>
<dd><a href="3_2_release_notes.html">Ruby on Rails 3.2 發佈記</a></dd>
<dd><a href="3_1_release_notes.html">Ruby on Rails 3.1 發佈記</a></dd>
<dd><a href="3_0_release_notes.html">Ruby on Rails 3.0 發佈記</a></dd>
<dd><a href="2_3_release_notes.html">Ruby on Rails 2.3 發佈記</a></dd>
<dd><a href="2_2_release_notes.html">Ruby on Rails 2.2 發佈記</a></dd>
<dt>Rails 指南翻譯術語</dt>
<dd><a href="translation_terms.html">翻譯術語</a></dd>
</dl>
</div>
</li>
<li><a class="nav-item" href="//github.com/docrails-tw/guides">貢獻翻譯</a></li>
<li><a class="nav-item" href="contributing_to_ruby_on_rails.html">貢獻</a></li>
<li><a class="nav-item" href="credits.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">Rails 起步走</option>
</optgroup>
<optgroup label="Models">
<option value="active_record_basics.html">Active Record 基礎</option>
<option value="active_record_migrations.html">Active Record 遷移</option>
<option value="active_record_validations.html">Active Record 驗證</option>
<option value="active_record_callbacks.html">Active Record 回呼</option>
<option value="association_basics.html">Active Record 關聯</option>
<option value="active_record_querying.html">Active Record 查詢</option>
</optgroup>
<optgroup label="Views">
<option value="layouts_and_rendering.html">Rails 算繪與版型</option>
<option value="form_helpers.html">Action View 表單輔助方法</option>
</optgroup>
<optgroup label="Controllers">
<option value="action_controller_overview.html">Action Controller 綜覽</option>
<option value="routing.html">Rails 路由:深入淺出</option>
</optgroup>
<optgroup label="深入了解">
<option value="active_support_core_extensions.html">Active Support 核心擴展</option>
<option value="i18n.html">Rails 國際化 API</option>
<option value="action_mailer_basics.html">Action Mailer 基礎</option>
<option value="active_job_basics.html">Active Job 基礎</option>
<option value="security.html">Rails 安全指南</option>
<option value="debugging_rails_applications.html">除錯 Rails 應用程式</option>
<option value="configuring.html">Rails 應用程式設定</option>
<option value="command_line.html">Rake 任務與 Rails 命令列工具</option>
<option value="asset_pipeline.html">Asset Pipeline</option>
<option value="working_with_javascript_in_rails.html">在 Rails 使用 JavaScript</option>
<option value="constant_autoloading_and_reloading.html">Constant Autoloading and Reloading</option>
</optgroup>
<optgroup label="擴充 Rails">
<option value="rails_on_rack.html">Rails on Rack</option>
<option value="generators.html">客製與新建 Rails 產生器</option>
<option value="rails_application_templates.html">Rails 應用程式模版</option>
</optgroup>
<optgroup label="貢獻 Ruby on Rails">
<option value="contributing_to_ruby_on_rails.html">貢獻 Ruby on Rails</option>
<option value="api_documentation_guidelines.html">API 文件準則</option>
<option value="ruby_on_rails_guides_guidelines.html">Ruby on Rails 指南準則</option>
</optgroup>
<optgroup label="維護方針">
<option value="maintenance_policy.html">維護方針</option>
</optgroup>
<optgroup label="發佈記">
<option value="upgrading_ruby_on_rails.html">升級 Ruby on Rails</option>
<option value="4_2_release_notes.html">Ruby on Rails 4.2 發佈記</option>
<option value="4_1_release_notes.html">Ruby on Rails 4.1 發佈記</option>
<option value="4_0_release_notes.html">Ruby on Rails 4.0 發佈記</option>
<option value="3_2_release_notes.html">Ruby on Rails 3.2 發佈記</option>
<option value="3_1_release_notes.html">Ruby on Rails 3.1 發佈記</option>
<option value="3_0_release_notes.html">Ruby on Rails 3.0 發佈記</option>
<option value="2_3_release_notes.html">Ruby on Rails 2.3 發佈記</option>
<option value="2_2_release_notes.html">Ruby on Rails 2.2 發佈記</option>
</optgroup>
<optgroup label="Rails 指南翻譯術語">
<option value="translation_terms.html">翻譯術語</option>
</optgroup>
</select>
</li>
</ul>
</div>
</div>
</div>
<hr class="hide">
<div id="feature">
<div class="wrapper">
<h2>A Guide to 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, and integration 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="#the-test-environment">The Test Environment</a></li>
<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-low-down-on-fixtures">The Low-Down on Fixtures</a></li>
</ul>
</li>
<li>
<a href="#unit-testing-your-models">Unit Testing your Models</a>
<ul>
<li><a href="#maintaining-the-test-database-schema">Maintaining the test database schema</a></li>
<li><a href="#running-tests">Running Tests</a></li>
<li><a href="#what-to-include-in-your-unit-tests">What to Include in Your Unit Tests</a></li>
<li><a href="#available-assertions">Available Assertions</a></li>
<li><a href="#rails-specific-assertions">Rails Specific Assertions</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="#the-four-hashes-of-the-apocalypse">The Four 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-templates-and-layouts">Testing Templates and Layouts</a></li>
<li><a href="#a-fuller-functional-test-example">A Fuller Functional Test Example</a></li>
<li><a href="#testing-views">Testing Views</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="#integration-testing-examples">Integration Testing Examples</a></li>
</ul>
</li>
<li><a href="#rake-tasks-for-running-your-tests">Rake Tasks for Running your Tests</a></li>
<li><a href="#brief-note-about-minitest">Brief Note About <code>Minitest</code></a></li>
<li><a href="#setup-and-teardown">Setup and Teardown</a></li>
<li><a href="#testing-routes">Testing Routes</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-testing">Functional Testing</a></li>
</ul>
</li>
<li><a href="#testing-helpers">Testing helpers</a></li>
<li><a href="#other-testing-approaches">Other Testing Approaches</a></li>
</ol>
</div>
</div>
</div>
<div id="container">
<div class="wrapper">
<div id="mainCol">
<h3 id="why-write-tests-for-your-rails-applications-questionmark">1 Why Write Tests for your Rails Applications?</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 simply 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">2 Introduction to Testing</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. 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><h4 id="the-test-environment">2.1 The Test Environment</h4><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. Tests can mangle test data with confidence, that won't touch the data in the development or production databases.</p><h4 id="rails-sets-up-for-testing-from-the-word-go">2.2 Rails Sets up for Testing from the Word Go</h4><p>Rails creates a <code>test</code> folder 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 folder then you shall see:</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
$ ls -F test
controllers/ helpers/ mailers/ test_helper.rb
fixtures/ integration/ models/
</pre>
</div>
<p>The <code>models</code> directory is meant to hold tests for your models, the <code>controllers</code> directory is meant to hold tests for your controllers and the <code>integration</code> directory is meant to hold tests that involve any number of controllers interacting.</p><p>Fixtures are a way of organizing test data; they reside in the <code>fixtures</code> folder.</p><p>The <code>test_helper.rb</code> file holds the default configuration for your tests.</p><h4 id="the-low-down-on-fixtures">2.3 The Low-Down on Fixtures</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="http://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html">fixture api documentation</a>.</p><h5 id="what-are-fixtures-questionmark">2.3.1 What Are Fixtures?</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 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 fixture stubs will be automatically created and placed in this directory.</p><h5 id="yaml">2.3.2 YAML</h5><p>YAML-formatted fixtures are a very 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 space. You can place comments in a fixture file by using the # character in the first column. Keys which resemble YAML keywords such as 'yes' and 'no' are quoted so that the YAML Parser correctly interprets them.</p><p>If you are working with <a href="/association_basics.html">associations</a>, you can simply
define a reference node between two different fixtures. Here's an example with
a belongs_to/has_many 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
one:
title: Welcome to Rails!
body: Hello world!
category: about
</pre>
</div>
<p>Note: For associations to reference one another by name, you cannot specify the <code>id:</code>
attribute on the fixtures. Rails will auto assign a primary key to be consistent between
runs. If you manually specify an <code>id:</code> attribute, this behavior will not work. For more
information on this association behavior please read the
<a href="http://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html">fixture api documentation</a>.</p><h5 id="erb-in-it-up">2.3.3 ERB'in It Up</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">2.3.4 Fixtures in Action</h5><p>Rails by default automatically loads all fixtures from the <code>test/fixtures</code> folder for your models and controllers test. Loading involves three steps:</p>
<ul>
<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 variable in case you want to access it directly</li>
</ul>
<h5 id="fixtures-are-active-record-objects">2.3.5 Fixtures are Active Record objects</h5><p>Fixtures are instances of Active Record. As mentioned in point #3 above, you can access the object directly because it is automatically setup as a local variable 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
email(david.girlfriend.email, david.location_tonight)
</pre>
</div>
<h3 id="unit-testing-your-models">3 Unit Testing your Models</h3><p>In Rails, models tests are what you write to test your models.</p><p>For this guide we will be using Rails <em>scaffolding</em>. It will create the model, a migration, controller and views for the new resource in a single operation. It will also create a full test suite following Rails best practices. We will be using examples from this generated code and will be supplementing it with additional examples where necessary.</p><div class="note"><p>For more information on Rails <em>scaffolding</em>, refer to <a href="getting_started.html">Getting Started with Rails</a></p></div><p>When you use <code>rails generate scaffold</code>, for a resource among other things it creates a test stub in the <code>test/models</code> folder:</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
$ bin/rails generate scaffold 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>As you know by now, <code>test_helper.rb</code> specifies the default configuration to run our tests. This is included with all the tests, so any methods added to this file are available to all your 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>. You'll see those methods a little later in this guide.</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> (case sensitive) is simply called a test. So, <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 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,</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
test "the truth" do
assert true
end
</pre>
</div>
<p>acts as if you had written</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
def test_the_truth
assert true
end
</pre>
</div>
<p>only the <code>test</code> macro allows a more readable test name. You can still use regular method definitions though.</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. Odd ones need <code>define_method</code> and <code>send</code> calls, but formally there's no restriction.</p></div><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
assert true
</pre>
</div>
<p>This line of code is called an <em>assertion</em>. 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 contains one or more assertions. Only when all the assertions are successful will the test pass.</p><h4 id="maintaining-the-test-database-schema">3.1 Maintaining the test database schema</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. If so, 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.</p><h4 id="running-tests">3.2 Running Tests</h4><p>Running a test is as simple as invoking the file containing the test cases through <code>rake test</code> command.</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
$ bin/rake test test/models/article_test.rb
.
Finished tests in 0.009262s, 107.9680 tests/s, 107.9680 assertions/s.
1 tests, 1 assertions, 0 failures, 0 errors, 0 skips
</pre>
</div>
<p>You can also run a particular test method from the test case by running the test and providing the <code>test method name</code>.</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
$ bin/rake test test/models/article_test.rb test_the_truth
.
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>This will run all test methods from the test case. Note that <code>test_helper.rb</code> is in the <code>test</code> directory, hence this directory needs to be added to the load path using the <code>-I</code> switch.</p><p>The <code>.</code> (dot) above indicates a passing test. When a test fails you see an <code>F</code>; when a test throws an error you see an <code>E</code> in its place. The last line of the output is the summary.</p><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.</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
$ bin/rake test test/models/article_test.rb test_should_not_save_article_without_title
F
Finished tests in 0.044632s, 22.4054 tests/s, 22.4054 assertions/s.
1) Failure:
test_should_not_save_article_without_title(ArticleTest) [test/models/article_test.rb:6]:
Failed assertion, no message given.
1 tests, 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>1)</code> along with the name of the failing test. The next few lines contain the stack trace followed by a message which 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">
1) Failure:
test_should_not_save_article_without_title(ArticleTest) [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 < ActiveRecord::Base
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">
$ bin/rake test test/models/article_test.rb test_should_not_save_article_without_title
.
Finished tests in 0.047721s, 20.9551 tests/s, 20.9551 assertions/s.
1 tests, 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 <em>Test-Driven Development</em> (TDD).</p><div class="info"><p>Many Rails developers practice <em>Test-Driven Development</em> (TDD). This is an excellent way to build up a test suite that exercises every part of your application. TDD is beyond the scope of this guide, but one place to start is with <a href="http://andrzejonsoftware.blogspot.com/2007/05/15-tdd-steps-to-create-rails.html">15 TDD steps to create a Rails application</a>.</p></div><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">
$ bin/rake test test/models/article_test.rb test_should_report_error
E
Finished tests in 0.030974s, 32.2851 tests/s, 0.0000 assertions/s.
1) Error:
test_should_report_error(ArticleTest):
NameError: undefined local variable or method `some_undefined_variable' for #<ArticleTest:0x007fe32e24afe0>
test/models/article_test.rb:10:in `block in <class:ArticleTest>'
1 tests, 0 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 alphabetical 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. simply set the <code>BACKTRACE</code> environment variable to enable this
behavior:</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
$ BACKTRACE=1 bin/rake test test/models/article_test.rb
</pre>
</div>
<h4 id="what-to-include-in-your-unit-tests">3.3 What to Include in Your Unit Tests</h4><p>Ideally, you would like to include a test for everything which could possibly break. It's a good practice to have at least one test for each of your validations and at least one test for every method in your model.</p><h4 id="available-assertions">3.4 Available Assertions</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>There are a bunch of different types of assertions you can use.
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. It's not required.</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( expecting, 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( expecting, 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_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_nothing_raised( exception1, exception2, ... ) { block }</code></td>
<td>Ensures that the given block doesn't raise 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 or descends from <code>class</code>.</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>assert_send( array, [msg] )</code></td>
<td>Ensures that executing the method listed in <code>array[1]</code> on the object in <code>array[0]</code> with the parameters of <code>array[2 and up]</code> is true. This one is weird eh?</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 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">3.5 Rails Specific Assertions</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><code>assert_difference(expressions, difference = 1, message = nil) {...}</code></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><code>assert_no_difference(expressions, message = nil, &amp;block)</code></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><code>assert_recognizes(expected_options, path, extras={}, message=nil)</code></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><code>assert_generates(expected_path, options, defaults={}, extras = {}, message=nil)</code></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><code>assert_response(type, message = nil)</code></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="http://rubydoc.info/github/rack/rack/master/Rack/Utils#SYMBOL_TO_STATUS_CODE-constant">mapping</a> works.</td>
</tr>
<tr>
<td><code>assert_redirected_to(options = {}, message=nil)</code></td>
<td>Assert 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>
<tr>
<td><code>assert_template(expected = nil, message=nil)</code></td>
<td>Asserts that the request was rendered with the appropriate template file.</td>
</tr>
</tbody>
</table>
<p>You'll see the usage of some of these assertions in the next chapter.</p><h3 id="functional-tests-for-your-controllers">4 Functional Tests for Your Controllers</h3><p>In Rails, testing the various actions of a single controller is called writing functional tests for that controller. Controllers handle the incoming web requests to your application and eventually respond with a rendered view.</p><h4 id="what-to-include-in-your-functional-tests">4.1 What to Include in your Functional Tests</h4><p>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 stored in the response template?</li>
<li>was the appropriate message displayed to the user in the view?</li>
</ul>
<p>Now that we have used Rails scaffold generator for our <code>Article</code> resource, it has already created the controller code and tests. You can take look at the file <code>articles_controller_test.rb</code> in the <code>test/controllers</code> directory.</p><p>Let me take you through one such test, <code>test_should_get_index</code> from the file <code>articles_controller_test.rb</code>.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class ArticlesControllerTest < ActionController::TestCase
test "should get index" do
get :index
assert_response :success
assert_not_nil assigns(:articles)
end
end
</pre>
</div>
<p>In the <code>test_should_get_index</code> test, Rails simulates a request on the action called <code>index</code>, making sure the request was successful and also ensuring that it assigns a valid <code>articles</code> instance variable.</p><p>The <code>get</code> method kicks off the web request and populates the results into the response. It accepts 4 arguments:</p>
<ul>
<li>The action of the controller you are requesting. This can be in the form of a string or a symbol.</li>
<li>An optional hash of request parameters to pass into the action (eg. query string parameters or article variables).</li>
<li>An optional hash of session variables to pass along with the request.</li>
<li>An optional hash of flash values.</li>
</ul>
<p>Example: Calling the <code>:show</code> action, passing an <code>id</code> of 12 as the <code>params</code> and setting a <code>user_id</code> of 5 in the session:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
get(:show, {'id' => "12"}, {'user_id' => 5})
</pre>
</div>
<p>Another example: Calling the <code>:view</code> action, passing an <code>id</code> of 12 as the <code>params</code>, this time with no session, but with a flash message.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
get(:view, {'id' => '12'}, nil, {'message' => 'booya!'})
</pre>
</div>
<div class="note"><p>If you try running <code>test_should_create_article</code> test from <code>articles_controller_test.rb</code> it will fail on account of the newly added model level validation and rightly so.</p></div><p>Let us modify <code>test_should_create_article</code> test in <code>articles_controller_test.rb</code> so that all our test pass:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
test "should create article" do
assert_difference('Article.count') do
post :create, article: {title: 'Some title'}
end
assert_redirected_to article_path(assigns(:article))
end
</pre>
</div>
<p>Now you can try running all the tests and they should pass.</p><h4 id="available-request-types-for-functional-tests">4.2 Available Request Types for Functional Tests</h4><p>If you're familiar with the HTTP protocol, you'll know that <code>get</code> is a type of request. There are 6 request types supported in Rails functional tests:</p>
<ul>
<li><code>get</code></li>
<li><code>post</code></li>
<li><code>patch</code></li>
<li><code>put</code></li>
<li><code>head</code></li>
<li><code>delete</code></li>
</ul>
<p>All of request types are methods that you can use, however, you'll probably end up using the first two more often than the others.</p><div class="note"><p>Functional tests do not verify whether the specified request type should be accepted by the action. Request types in this context exist to make your tests more descriptive.</p></div><h4 id="the-four-hashes-of-the-apocalypse">4.3 The Four Hashes of the Apocalypse</h4><p>After a request has been made using one of the 6 methods (<code>get</code>, <code>post</code>, etc.) and processed, you will have 4 Hash objects ready for use:</p>
<ul>
<li>
<code>assigns</code> - Any objects that are stored as instance variables in actions for use in views.</li>
<li>
<code>cookies</code> - Any cookies that are set.</li>
<li>
<code>flash</code> - Any objects living in the flash.</li>
<li>
<code>session</code> - Any object living in session variables.</li>
</ul>
<p>As is the case with normal Hash objects, you can access the values by referencing the keys by string. You can also reference them by symbol name, except for <code>assigns</code>. For example:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
flash["gordon"] flash[:gordon]
session["shmession"] session[:shmession]
cookies["are_good_for_u"] cookies[:are_good_for_u]
# Because you can't use assigns[:something] for historical reasons:
assigns["something"] assigns(:something)
</pre>
</div>
<h4 id="instance-variables-available">4.4 Instance Variables Available</h4><p>You also have access to three instance variables in your functional tests:</p>
<ul>
<li>
<code>@controller</code> - The controller processing the request</li>
<li>
<code>@request</code> - The request</li>
<li>
<code>@response</code> - The response</li>
</ul>
<h4 id="setting-headers-and-cgi-variables">4.5 Setting Headers and CGI variables</h4><p><a href="http://tools.ietf.org/search/rfc2616#section-5.3">HTTP headers</a>
and
<a href="http://tools.ietf.org/search/rfc3875#section-4.1">CGI variables</a>
can be set directly on the <code>@request</code> instance variable:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
# setting a HTTP Header
@request.headers["Accept"] = "text/plain, text/html"
get :index # simulate the request with custom header
# setting a CGI variable
@request.headers["HTTP_REFERER"] = "http://example.com/home"
post :create # simulate the request with custom env variable
</pre>
</div>
<h4 id="testing-templates-and-layouts">4.6 Testing Templates and Layouts</h4><p>If you want to make sure that the response rendered the correct template and layout, you can use the <code>assert_template</code>
method:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
test "index should render correct template and layout" do
get :index
assert_template :index
assert_template layout: "layouts/application"
end
</pre>
</div>
<p>Note that you cannot test for template and layout at the same time, with one call to <code>assert_template</code> method.
Also, for the <code>layout</code> test, you can give a regular expression instead of a string, but using the string, makes
things clearer. On the other hand, you have to include the "layouts" directory name even if you save your layout
file in this standard layout directory. Hence,</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
assert_template layout: "application"
</pre>
</div>
<p>will not work.</p><p>If your view renders any partial, when asserting for the layout, you have to assert for the partial at the same time.
Otherwise, assertion will fail.</p><p>Hence:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
test "new should render correct layout" do
get :new
assert_template layout: "layouts/application", partial: "_form"
end
</pre>
</div>
<p>is the correct way to assert for the layout when the view renders a partial with name <code>_form</code>. Omitting the <code>:partial</code> key in your <code>assert_template</code> call will complain.</p><h4 id="a-fuller-functional-test-example">4.7 A Fuller Functional Test Example</h4><p>Here's another example that uses <code>flash</code>, <code>assert_redirected_to</code>, and <code>assert_difference</code>:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
test "should create article" do
assert_difference('Article.count') do
post :create, article: {title: 'Hi', body: 'This is my first article.'}
end
assert_redirected_to article_path(assigns(:article))
assert_equal 'Article was successfully created.', flash[:notice]
end
</pre>
</div>
<h4 id="testing-views">4.8 Testing Views</h4><p>Testing the response to your request by asserting the presence of key HTML elements and their content is a useful way to test the views of your application. The <code>assert_select</code> assertion allows you to do this by using a simple yet powerful syntax.</p><div class="note"><p>You may find references to <code>assert_tag</code> in other documentation. This has been removed in 4.2. Use <code>assert_select</code> instead.</p></div><p>There are two forms of <code>assert_select</code>:</p><p><code>assert_select(selector, [equality], [message])</code> ensures that the equality condition is met on the selected elements through the selector. The selector may be a CSS selector expression (String) or an expression with substitution values.</p><p><code>assert_select(element, selector, [equality], [message])</code> ensures that the equality condition is met on all the selected elements through the selector starting from the <em>element</em> (instance of <code>Nokogiri::XML::Node</code> or <code>Nokogiri::XML::NodeSet</code>) and its descendants.</p><p>For example, you could verify the contents on the title element in your response with:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
assert_select 'title', "Welcome to Rails Testing Guide"
</pre>
</div>
<p>You can also use nested <code>assert_select</code> blocks. In this case the inner <code>assert_select</code> runs the assertion on the complete collection of elements selected by the outer <code>assert_select</code> block:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
assert_select 'ul.navigation' do
assert_select 'li.menu_item'
end
</pre>
</div>
<p>Alternatively the collection of elements selected by the outer <code>assert_select</code> may be iterated through so that <code>assert_select</code> may be called separately for each element. Suppose for example that the response contains two ordered lists, each with four list elements then the following tests will both pass.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
assert_select "ol" do |elements|
elements.each do |element|
assert_select element, "li", 4
end
end
assert_select "ol" do
assert_select "li", 8
end
</pre>
</div>
<p>The <code>assert_select</code> assertion is quite powerful. For more advanced usage, refer to its <a href="https://github.com/rails/rails-dom-testing/blob/master/lib/rails/dom/testing/assertions/selector_assertions.rb">documentation</a>.</p><h5 id="additional-view-based-assertions">4.8.1 Additional View-Based Assertions</h5><p>There are more assertions that are primarily used in testing views:</p>
<table>
<thead>
<tr>
<th>Assertion</th>
<th>Purpose</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>assert_select_email</code></td>
<td>Allows you to make assertions on the body of an e-mail.</td>
</tr>
<tr>
<td><code>assert_select_encoded</code></td>
<td>Allows you to make assertions on encoded HTML. It does this by un-encoding the contents of each element and then calling the block with all the un-encoded elements.</td>
</tr>
<tr>
<td>
<code>css_select(selector)</code> or <code>css_select(element, selector)</code>
</td>
<td>Returns an array of all the elements selected by the <em>selector</em>. In the second variant it first matches the base <em>element</em> and tries to match the <em>selector</em> expression on any of its children. If there are no matches both variants return an empty array.</td>
</tr>
</tbody>
</table>
<p>Here's an example of using <code>assert_select_email</code>:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
assert_select_email do
assert_select 'small', 'Please click the "Unsubscribe" link if you want to opt-out.'
end
</pre>
</div>
<h3 id="integration-testing">5 Integration Testing</h3><p>Integration tests are used to test the interaction among any number of controllers. They are generally used to test important work flows within your application.</p><p>Unlike Unit and Functional tests, integration tests have to be explicitly created under the 'test/integration' folder within your application. Rails provides a generator to create an integration test skeleton for you.</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
$ bin/rails generate integration_test user_flows
exists test/integration/
create test/integration/user_flows_test.rb
</pre>
</div>
<p>Here's what a freshly-generated integration test looks like:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
require 'test_helper'
class UserFlowsTest < ActionDispatch::IntegrationTest
# test "the truth" do
# assert true
# end
end
</pre>
</div>
<p>Integration tests inherit from <code>ActionDispatch::IntegrationTest</code>. This makes available some additional helpers to use in your integration tests. Also you need to explicitly include the fixtures to be made available to the test.</p><h4 id="helpers-available-for-integration-tests">5.1 Helpers Available for Integration Tests</h4><p>In addition to the standard testing helpers, there are some additional helpers available to integration tests:</p>
<table>
<thead>
<tr>
<th>Helper</th>
<th>Purpose</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>https?</code></td>
<td>Returns <code>true</code> if the session is mimicking a secure HTTPS request.</td>
</tr>
<tr>
<td><code>https!</code></td>
<td>Allows you to mimic a secure HTTPS request.</td>
</tr>
<tr>
<td><code>host!</code></td>
<td>Allows you to set the host name to use in the next request.</td>
</tr>
<tr>
<td><code>redirect?</code></td>
<td>Returns <code>true</code> if the last request was a redirect.</td>
</tr>
<tr>
<td><code>follow_redirect!</code></td>
<td>Follows a single redirect response.</td>
</tr>
<tr>
<td><code>request_via_redirect(http_method, path, [parameters], [headers])</code></td>
<td>Allows you to make an HTTP request and follow any subsequent redirects.</td>
</tr>
<tr>
<td><code>post_via_redirect(path, [parameters], [headers])</code></td>
<td>Allows you to make an HTTP POST request and follow any subsequent redirects.</td>
</tr>
<tr>
<td><code>get_via_redirect(path, [parameters], [headers])</code></td>
<td>Allows you to make an HTTP GET request and follow any subsequent redirects.</td>
</tr>
<tr>
<td><code>patch_via_redirect(path, [parameters], [headers])</code></td>
<td>Allows you to make an HTTP PATCH request and follow any subsequent redirects.</td>
</tr>
<tr>
<td><code>put_via_redirect(path, [parameters], [headers])</code></td>
<td>Allows you to make an HTTP PUT request and follow any subsequent redirects.</td>
</tr>
<tr>
<td><code>delete_via_redirect(path, [parameters], [headers])</code></td>
<td>Allows you to make an HTTP DELETE request and follow any subsequent redirects.</td>
</tr>
<tr>
<td><code>open_session</code></td>
<td>Opens a new session instance.</td>
</tr>
</tbody>
</table>
<h4 id="integration-testing-examples">5.2 Integration Testing Examples</h4><p>A simple integration test that exercises multiple controllers:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">