|
1 | 1 | Feature: view spec
|
2 | 2 |
|
3 |
| - View specs live in spec/views and render view templates in isolation. |
| 3 | + View specs are marked by `:type => :view` |
| 4 | + or if you have set `config.infer_spec_type_from_file_location!` |
| 5 | + by placing them in `spec/views`. |
| 6 | + |
| 7 | + Use them to test the content of view templates |
| 8 | + without invoking a specific controller. |
| 9 | + They generally follow three steps: |
| 10 | + |
| 11 | + ```ruby |
| 12 | + assign(:widget, Widget.new) # sets @widget = Widget.new in the view template |
| 13 | + |
| 14 | + render |
| 15 | + |
| 16 | + expect(rendered).to match(/text/) |
| 17 | + ``` |
| 18 | + |
| 19 | + 1. Use the `assign` method to set instance variables in the view. |
| 20 | + |
| 21 | + 2. Use the `render` method to render the view. |
| 22 | + |
| 23 | + 3. Set expectations against the resulting rendered template. |
4 | 24 |
|
5 | 25 | Scenario: View specs render the described view file
|
6 | 26 | Given a file named "spec/views/widgets/index.html.erb_spec.rb" with:
|
@@ -73,6 +93,34 @@ Feature: view spec
|
73 | 93 | When I run `rspec spec/views`
|
74 | 94 | Then the examples should all pass
|
75 | 95 |
|
| 96 | + Scenario: View specs can render templates in layouts |
| 97 | + Given a file named "spec/views/widgets/widget.html.erb_spec.rb" with: |
| 98 | + """ruby |
| 99 | + require "rails_helper" |
| 100 | +
|
| 101 | + RSpec.describe "rendering the widget template" do |
| 102 | + context "with the inventory layout" do |
| 103 | + it "displays the widget" do |
| 104 | + assign(:widget, Widget.create!(:name => "slicer")) |
| 105 | +
|
| 106 | + render :template => "widgets/widget.html.erb", :layout => "layouts/inventory" |
| 107 | +
|
| 108 | + expect(rendered).to match /slicer/ |
| 109 | + end |
| 110 | + end |
| 111 | + end |
| 112 | + """ |
| 113 | + And a file named "app/views/widgets/widget.html.erb" with: |
| 114 | + """ |
| 115 | + <h2><%= @widget.name %></h2> |
| 116 | + """ |
| 117 | + And a file named "app/views/layouts/inventory.html.erb" with: |
| 118 | + """ |
| 119 | + <%= yield %> |
| 120 | + """ |
| 121 | + When I run `rspec spec/views` |
| 122 | + Then the examples should all pass |
| 123 | + |
76 | 124 | Scenario: View specs can have description that includes the format and handler
|
77 | 125 | Given a file named "spec/views/widgets/widget.xml.erb_spec.rb" with:
|
78 | 126 | """ruby
|
|
0 commit comments