Code tagged with rspec

Spec Helpers for Login Testing

Posted by Chad Humphries about 1 year ago / Source: http://pastie.caboo.se/29577
Found about the internet...

module UserSpecHelpers
  module ClassMethods
    def require_login_and_correct_user(action, &request)
      require_login action, &request
      require_user action, &request
    end

    def require_login(action, &request)
      specify "when calling #{action} should redirect to the login screen if the User is not logged in" do
        controller.should_redirect_to :controller => "sessions", :action => "new"
        instance_eval &request
      end
    end

    def require_user(action, &request)
      specify "when calling #{action} should render a 403 if the logged in User isn't the User requested" do
        mock_user = mock("user")
        login_as mock_user, "2"
        controller.should_render :status => 403, :nothing => true
        User.stub!(:find).and_return(mock("user2"))
        instance_eval &request
      end
    end
    
    def should_find_user_on(http_verb)
      specify "should find the relevant User" do
        User.should_receive(:find).with("1").and_return mock_user
        send("do_#{http_verb}")
      end
    end
  end
  
  def self.included(receiver)
    receiver.extend ClassMethods
  end
  
  def login_as(user, id = "1")
    user.stub!(:id).and_return(id)
    user.stub!(:to_param).and_return(id)
    controller.send :current_user=, user
  end
end
Language Ruby / Tagged with rspec, rails, testing

Pre 0.8.0 Validation Checker for RSpec

Nothing special, just a simple helper I threw together in a few minutes.  It is used in model tests to verify that a column is required.  A few usages follow.

  def should_require_attribute(model, attrib_name, error_messages=[], invalid_value=nil)
    # Collect the valid value
    valid_value = model.send(attrib_name)
    error_messages = error_messages.to_a.sort
    
    # Set it to nil
    model.send("#{attrib_name.to_s}=", invalid_value)

    model.should_not_be_valid
    model.should_have(error_messages.size).errors
    model.errors.on(attrib_name).to_a.sort.should == error_messages
    
    # Put things back where you found them
    model.send("#{attrib_name.to_s}=", valid_value)
    model.should_be_valid
  end

# Simple case
specify "should be invalid without state" do
   should_require_attribute(your_model, :state, "is required")   
end

# More than one error expected
specify "should require a valid email address" do
   should_require_attribute(your_model, :email_address, ["is required", "should be a valid format"])   
end

# Invalid value other than nil
specify "should require a non .gov email address" do
   should_require_attribute(your_model, :email_address, "can't contain .gov domains", "bigbrother@government.gov")   
end
Language Ruby / Tagged with rspec, activerecord, rails