Skip to content

Instantly share code, notes, and snippets.

@xirukitepe
Created November 7, 2012 07:45
Show Gist options
  • Save xirukitepe/4030061 to your computer and use it in GitHub Desktop.
Save xirukitepe/4030061 to your computer and use it in GitHub Desktop.
Example rspec test for a view
describe "events/index" do
it "renders _event partial for each event" do
assign(:events, [stub_model(Event), stub_model(Event)])
render
view.should render_template(:partial => "_event", :count => 2)
end
end
describe "events/show" do
it "displays the event location" do
assign(:event, stub_model(Event,
:location => "Chicago"
))
render
rendered.should contain("Chicago")
end
end
#View specs infer the controller name and path from the path to the view template. e.g. if the template is "events/index.html.erb" then:
controller.controller_path == "events"
controller.request.path_parameters[:controller] == "events"
#This means that most of the time you don't need to set these values. When spec'ing a partial that is included across different controllers, #you may need to override these values before rendering the view.
#To provide a layout for the render, you'll need to specify both the template and the layout explicitly. For example:
render :template => "events/show", :layout => "layouts/application"
assign(key, val)
#Use this to assign values to instance variables in the view:
assign(:widget, stub_model(Widget))
render
#The code above assigns stub_model(Widget) to the @widget variable in the view, and then renders the view.
#Note that because view specs mix in ActionView::TestCase behavior, any instance variables you set will be transparently propagated into your #views (similar to how instance variables you set in controller actions are made available in views). For example:
@widget = stub_model(Widget)
render # @widget is available inside the view
#RSpec doesn't officially support this pattern, which only works as a side-effect of the inclusion of ActionView::TestCase. Be aware that it #may be made unavailable in the future.
#Upgrade note
# rspec-rails-1.x
assigns[key] = value
# rspec-rails-2.x
assign(key, value)
#rendered
#This represents the rendered view.
render
rendered.should =~ /Some text expected to appear on the page/
#Upgrade note
# rspec-rails-1.x
render
response.should xxx
# rspec-rails-2.x
render
rendered.should xxx
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment