Note that there are some explanatory texts on larger screens.

plurals
  1. POUnit testing strangeness with Rails fixtures
    text
    copied!<p>Sorry for the vague question title, but I'm having a hard time trying to distil what I'm asking into a one-liner... </p> <p>I have a couple of simple Rails (3.1) models generated via <code>rails g scaffold</code>, which I'm trying to unit test. They are defined in the following way:</p> <pre><code>class ModelA &lt; ActiveRecord::Base validates_presence_of :field1, :field2 validates_uniqueness_of :field1 end class ModelB &lt; ActiveRecord::Base validates_presence_of :field1 validates_uniqueness_of :field1 end </code></pre> <p>I have a couple of fixtures for each model, i.e:</p> <pre><code>model_a_no_field1: field2: test model_a_no_field2: field1: test model_a_ok: field1: test field2: test </code></pre> <p>and</p> <pre><code>model_b_no_field1: model_b_ok: field1: test </code></pre> <p>My unit tests are testing these validations:</p> <pre><code>class ModelATest &lt; ActiveSupport::TestCase test "field1 should be present" do assert !model_as(:model_a_no_field1).valid? end test "field2 should be present" do assert !model_as(:model_a_no_field2).valid? end test "field1 should be unique" do model_a = model_as(:model_a_ok) model_a.save assert !model_as(:model_a_ok).valid? end end </code></pre> <p>These tests all pass correctly. However, my similar unit tests for <code>ModelB</code>:</p> <pre><code>class ModelBTest &lt; ActiveSupport::TestCase test "field1 should be present" do assert !model_bs(:model_b_no_field1).valid? end test "field1 should be unique" do model_b = model_bs(:model_b_ok) model_b.save assert !model_bs(:model_b_ok).valid? end end </code></pre> <p>Fail on the second test (testing the uniqueness).</p> <p>I'm almost certain this is to do with the empty YAML fixture for <code>model_b_no_field1</code>, but I'm not sure. I can cause the test to pass by replacing the test method body with</p> <pre><code>test "field1 should be unique" do model_b = model_bs(:model_b_ok) model_b.save model_b2 = ModelB.new assert !model_b2.valid? end </code></pre> <p>Which is fine, but I'd like to understand what's happening here.</p>
 

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