Skip to content

Instantly share code, notes, and snippets.

@xirukitepe
Created November 7, 2012 07:04
Show Gist options
  • Save xirukitepe/4029931 to your computer and use it in GitHub Desktop.
Save xirukitepe/4029931 to your computer and use it in GitHub Desktop.
example on how to rspec test a controler
#with fixtures
describe WidgetsController do
describe "GET index" do
fixtures :widgets
it "assigns all widgets to @widgets" do
get :index
assigns(:widgets).should eq(Widget.all)
end
end
end
#with a factory
describe WidgetsController do
describe "GET index" do
it "assigns all widgets to @widgets" do
widget = FactoryGirl.create(:widget)
get :index
assigns(:widgets).should eq([widget])
end
end
end
#with stubs
describe WidgetsController do
describe "GET index" do
it "assigns all widgets to @widgets" do
widget = stub_model(Widget)
Widget.stub(:all) { [widget] }
get :index
assigns(:widgets).should eq([widget])
end
end
end
#matchers
#In addition to the stock matchers from rspec-expectations, controller specs add these matchers, which delegate to rails' assertions:
response.should render_template(*args)
# => delegates to assert_template(*args)
response.should redirect_to(destination)
# => delegates to assert_redirected_to(destination)
#isolation from views
#RSpec's preferred approach to spec'ing controller behaviour is to isolate the controller from its collaborators. By default, therefore, #controller example groups do not render the views in your app. Due to the way Rails searches for view templates, the template still needs to #exist, but it won't actually be loaded.
#NOTE that this is different from rspec-rails-1 with rails-2, which did not require the presence of the file at all. Due to changes in rails-#3, this was no longer feasible in rspec-rails-2.
render_views
#If you prefer a more integrated approach, similar to that of Rails' functional tests, you can tell controller groups to render the views in the app with the render_views declaration:
describe WidgetsController do
render_views
# ...
#Upgrade note
render_views replaces integrate_views from rspec-rails-1.3
assigns
#Use assigns(key) to express expectations about instance variables that a controller assigns to the view in the course of an action:
get :index
assigns(:widgets).should eq(expected_value)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment