jeudi 21 février 2019

Rails 5: Why is my test failing despite proving in the console that it should pass?

I have two models Profile and ExternalLink. An external link belongs to a profile. A profile has many external links. The relationship is polymorphic.

    class ExternalLink < ApplicationRecord
      belongs_to :link_owner, polymorphic: true

      validates :url, presence: true, allow_blank: false, url: { schemes: ["https", "http"] }
    end

    class Profile < ApplicationRecord
      has_many :external_links, as: :link_owner, dependent: :destroy
      belongs_to :user
    end

I can add an external link to a profile in the console:

    user = User.create(name: "test user")
    user.profile = Profile.create
    user.profile.external_links << ExternalLink.create(url: "https://www.example.com/test")
    user.profile.external_links.count
    #=> 1

However, this fails when I run it as a test:

    test "a profile can have an external link" do
      user = User.create(name: "test user")
      user.profile = Profile.create
      user.profile.external_links << ExternalLink.create(url: "https://www.example.com/test")
      assert_equal 1, user.profile.external_links.count
    end

    Failure:
    ProfileTest#test_a_profile_can_have_an_external_link [/Users/jan_from_accounts/Rails/goosh/test/models/profile_test.rb:27]:
    Expected: 1
      Actual: 0

I believe that this is to do with a difference in the test environment. I have run rails db:reset RAILS_ENV=test but the test still fails.

Is there anything I've obviously done wrong? Why should the test fail yet I can add an external link successfully? in the console.

Aucun commentaire:

Enregistrer un commentaire