Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>It's complicated. Race conditions are so nasty precisely because they are so difficult to reproduce. Internally, <code>save</code> goes something like this:</p> <ol> <li>Validate.</li> <li>Write to database.</li> </ol> <p>So, to reproduce the timing problem, you'd need to arrange the two <code>save</code> calls to overlap like this (pseudo-Rails):</p> <pre><code>a.validate # first half of a.save b.validate # first half of b.save a.write_to_db # second half of a.save b.write_to_db # second half of b.save </code></pre> <p>but you can't open up the <code>save</code> method and fiddle with its internals quite so easily.</p> <p>But (and this is a big but), <a href="http://guides.rubyonrails.org/active_record_validations_callbacks.html#skipping-validations" rel="nofollow">you can skip the validations entirely</a>:</p> <blockquote> <p>Note that <code>save</code> also has the ability to skip validations if passed <code>:validate =&gt; false</code> as argument. This technique should be used with caution.</p> </blockquote> <p>So if you use</p> <pre><code>b.save(:validate =&gt; false) </code></pre> <p>you should get just the "write to database" half of <code>b</code>'s <code>save</code> and send your data to the database without validation. That should trigger a constraint violation in the database and I'm pretty sure that will raise an <a href="http://api.rubyonrails.org/classes/ActiveRecord/StatementInvalid.html" rel="nofollow">ActiveRecord::StatementInvalid</a> exception so I think you'll need to look for an exception rather than just a false return from <code>save</code>:</p> <pre><code>b.save(:validate =&gt; false).should raise_exception(ActiveRecord::StatementInvalid) </code></pre> <p>You can tighten that up to look for the specific exception message as well. I don't have anything handy to test this test with so try it out in the Rails console and adjust your spec appropriately.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload