Skip to content

Instantly share code, notes, and snippets.

@joanwolk
Created August 16, 2011 16:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joanwolk/1149454 to your computer and use it in GitHub Desktop.
Save joanwolk/1149454 to your computer and use it in GitHub Desktop.
RSpec controller test using cookies
class PreferencesController < ApplicationController
def update
@subdomain = cookies[:subdomain_name]
@preference = Preference.find_by_subdomain_name(@subdomain)
if @preference.update_attributes(params[:preference])
flash[:success] = "Preferences for #{params[:preference][:subdomain_name]} updated."
redirect_to spaces_path
else
@token = session[:token]
render :edit
end
end
end
describe PreferencesController do
describe "when logged in" do
before(:each) do
# Not shown: variables that don't appear in the relevant tests
@request.cookies[:subdomain_name] = "my_subdomain" # This line is crucial!
# The line that didn't work was as below:
# cookies[:subdomain_name] = "my_subdomain"
end
describe "actions on existing preferences" do
before(:each) do
# As a bonus, I can set the subdomain_name with the cookie here
@prefs = Preference.create!( subdomain_name: cookies[:subdomain_name],
access_token_string: session[:token],
expire_after_days: 30 )
@new_prefs = { :subdomain_name => cookies[:subdomain_name],
:access_token_string => session[:token],
:expire_after_days => 20 }
end
describe "PUT update" do
# But here's where the cookie is required, because
# the update method uses the cookie to find the record
it "should update the days to expiration" do
put :update, :id => @prefs, :preference => @new_prefs
@prefs.reload
@prefs.expire_after_days.should == @new_prefs[:expire_after_days].to_i
end
it "should redirect to the spaces page" do
put :update, :id => @prefs, :preference => @new_prefs
response.should redirect_to spaces_path
end
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment