kjs3
kjs3

Reputation: 6178

Rails 4: Why do fixtures make this test fail?

I have the test below and if there are any fixtures for this model it fails with total_unapproved and new_total being equal instead of new_total being one less. If I remove loading the fixtures in test_helper.rb or comment them out it runs as I expect.

Here's the class function that sets approvals to true. It definitely works.

def InviteRequest.approve_invites(number)
  inv_reqs = InviteRequest.where("approved = ?", false).first(number)
  inv_reqs.each do |inv_req|
    inv_req.approved = true
    inv_req.save
    inv_req.send_approved_email
  end
end

Here's the test that calls the above function.

require 'test_helper'

class InviteRequestTest < ActiveSupport::TestCase

  test "class method approve_invites(number) should approve 'number' InviteRequests" do
    # ensure there is at least one instance
    inv_req = InviteRequest.create(email: "[email protected]")

    # set all InviteRequests.approved to false
    InviteRequest.all.each {|r| r.approved = false; r.save}
    total_unapproved = InviteRequest.where("approved = ?", false).count
    Rails.logger.info "\nUnapproved Before: #{total_unapproved}"
    InviteRequest.approve_invites(1)
    new_total = InviteRequest.where("approved = ?", false).count
    Rails.logger.info "Unapproved After: #{new_total}\n"

    assert_equal total_unapproved - 1, new_total
  end 
end

Any idea why? I'm not using the fixtures in any other tests but maybe I will someday.

Upvotes: 0

Views: 1044

Answers (3)

Gee-Bee
Gee-Bee

Reputation: 3195

When you use rails generator for new model, fixture file is generated as well looking like this:

one: {}
# column: value
two: {}
#  column: value

When you run your tests using fixtures, rails tries to create this 2 empty records. If you have constraint in your migration (such as not null), your tests will fail for obvious reasons.

Solution: Comment out this empty records in your fixtures files or fill them with something sensible.

Upvotes: 0

kjs3
kjs3

Reputation: 6178

My fixtures weren't valid and changing them fixed the problem. I'm still not exactly sure how things were failing though. My fixtures looked like this:

one:
  email: MyString

two:
  email: MyString

This would fail my uniqueness validation and not save but I'm not sure why the newly created model wouldn't have 'approved' set to true and still be saved since it's correct.

Anyway, changing the fixtures to this fixed things.

one:
  email: [email protected]

two:
  email: [email protected]

Upvotes: 1

DNNX
DNNX

Reputation: 6255

Maybe validation fails when you're calling InviteRequest#save? Try to replace save with save! and check to see if the test still passes.

Upvotes: 0

Related Questions