Search code examples
ruby-on-railsruby-on-rails-4cloud9-ide

Console tells me object exists; rake test does not


I am new to ruby on rails and have worked through some tutorials. Now I'm trying to build an app of my own and encountering issues. Many I have been able to work work around, which is a great learning experience, but this one I'm stumped by.

I have created a model, migrated it, there's one model called CardSymbol, it consists of an id field and a name. I have this in my seeds.rb file which I have run.

CardSymbol.create!(name: "hat")

I can open up the rails console, type this in...

CardSymbol.find_by(name: "hat").id

...and I get 1, the primary key, this is what I expect. So I know the record is in the database.

And yet in one of my test.rb files, I have the exact same code, but when I run bundle exec rake test and I get

NoMethodError: undefined method `id' for nil:NilClass

So... this appears to be telling me it has failed to find the record that I know exists. I tried setting Rails.env in my test file to development or test, as "different environment" was all I could think of as a solution that fits the symptoms, but it didn't help. What am I missing here?

PS I'm pretty convinced the test code is not the issue but as multiple people have asked for it, I stripped it all back to the following & still got the error (note it's an error, not a test failure).

require 'test_helper'

class CardTypeTest < ActiveSupport::TestCase

  def setup
    @example_card_symbol = CardSymbol.find_by(name: "hat").id
  end

  test "should be valid" do
    assert 1==1
  end

end

Solution

  • In the test file in the setup method, add this line as the first line.

    Rails.application.load_seed
    

    This will then load the data from seeds.rb into the test database, and it all works.

    With thanks to Frederick Cheung whose answer pointed me in the right direction.