kfb
kfb

Reputation: 6542

Unit testing strangeness with Rails fixtures

Sorry for the vague question title, but I'm having a hard time trying to distil what I'm asking into a one-liner...

I have a couple of simple Rails (3.1) models generated via rails g scaffold, which I'm trying to unit test. They are defined in the following way:

class ModelA < ActiveRecord::Base
  validates_presence_of :field1, :field2
  validates_uniqueness_of :field1
end

class ModelB < ActiveRecord::Base
  validates_presence_of :field1
  validates_uniqueness_of :field1
end

I have a couple of fixtures for each model, i.e:

model_a_no_field1:
    field2: test

model_a_no_field2:
    field1: test

model_a_ok:
    field1: test
    field2: test

and

model_b_no_field1:

model_b_ok:
    field1: test

My unit tests are testing these validations:

class ModelATest < 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

These tests all pass correctly. However, my similar unit tests for ModelB:

class ModelBTest < 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

Fail on the second test (testing the uniqueness).

I'm almost certain this is to do with the empty YAML fixture for model_b_no_field1, but I'm not sure. I can cause the test to pass by replacing the test method body with

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

Which is fine, but I'd like to understand what's happening here.

Upvotes: 2

Views: 284

Answers (1)

Augusto
Augusto

Reputation: 30007

I think you're subverting the test infrastructure that rails creates for you. The models that you have in the yaml file should be valid, and if you want to test something that is invalid, create it in the test.

Creating the data in the test has the extra value of being very clear and concrete. Otherwise a dev would need to open the yaml file to understand what data you have and what is missing.

Upvotes: 3

Related Questions