[rspec-users] Question on SQL exceptions

Pat Maddox pat.maddox at gmail.com
Mon Mar 9 15:59:46 EDT 2009


ActiveRecord doesn't know anything about db constraint errors.  If one  
is violated, the error propagates up in the form of an exception.

Put a validates_uniqueness_of :login_name on your User class, and  
you'll get the behavior you want.  You can keep the db constraint in  
as a safety net against possible race conditions at the app layer.

Pat



On Mar 9, 2009, at 12:36 PM, James Byrne wrote:

> To prevent duplicate values in the DBMS I use a unique index on those
> columns.  I am testing that duplicate values cannot, in fact, be  
> added.
>
> This is the cucumber scenario:
>
>  Scenario: The legal name must be unique
>    Given I do have a user named "admin"
>      And the user named "admin" is authenticated
>      And the user named "admin" is authorized to "add" "entities"
>      And I do have an entity named "Myuser"
>      And the entity named "Myuser" has a legal name "Myuser Legal  
> Name"
>    When they visit the add a new entity page
>      And they enter valid entity data
>      And they enter the entity legal name "MyUser  LEGAL  NAME"
>      And I press "Create"
>    Then they should see a save error message
>
> This is the step definition that should be triggered:
>
> When /should see a save error message/ do
>  response.body.should =~ /errors? prohibited this (.*) from being
> saved/im
> end
>
> But what happens is that SQLite3 throws an SQL exception:
>  SQLite3::SQLException: column entity_legal_name is not unique:...;
>
> that is not caught by this controller:
>
>  def create
>    @entity = Entity.new(params[:entity])
>
>    # need this to strip out observer attributes for datebalks plugin
>    # see config/initializers/hash_addins.rb
>
>    @client = @entity.build_client(params[:client].datebalk!)
>
>    respond_to do |format|
>      if @entity.save
>        flash[:notice] = 'Client was successfully created.'
>        format.html { redirect_to(@client) }
>        format.xml  { render :xml => @client,
>          :status => :created, :location => @client }
>      else
>        format.html { render :action => "new" }
>        format.xml  { render :xml => @client.errors,
>          :status => :unprocessable_entity }
>      end
>    end
>
> I thought, probably incorrectly, that when #save is called then any
> errors are returned to the controller to handle.  This is evidently  
> not
> happening so can someone tell me how this is supposed to be handled?
> -- 
> Posted via http://www.ruby-forum.com/.
> _______________________________________________
> rspec-users mailing list
> rspec-users at rubyforge.org
> http://rubyforge.org/mailman/listinfo/rspec-users



More information about the rspec-users mailing list