简体   繁体   中英

How to test Rails model associations

Trying to test a module. It works when executed in rails console, but not when written as a test. Suppose the following:

  1. MyModel

    a) has_many :my_other_model

  2. MyOtherModel

    a) belongs to :my_model

Module example:

module MyModule

  def self.doit
    mine = MyModel.first
    mine.my_other_models.create!(attribute: 'Me')
  end

end

Now test:

require 'test_helper'

class MyModuleTest < ActiveSupport::TestCase

  test "should work" do
    assert MyModule.doit
  end

end

Returns:

NoMethodError: NoMethodError: undefined method `my_other_models' for nil:NilClass

Now try the same thing in the console:

rails c

MyModule.doit

Works just fine. But why not as a test?

Your test database is empty when you run this test, so calling MyModel.first is going to return nil , then you try to chain an unknown method to nil. What you'll probably want for your test suite is a fixture , which is just sample data. For now, you you can just create the first instance to get the test to work.

  test "should work" do
    MyModel.create #assuming the model is not validated
    assert MyModule.doit
  end

You could also refactor your module. Adding if mine will only try to create the other models if mine is not nil. That would get the test to pass, but negates the purpose of your test.

  def self.doit
    mine = MyModel.first
    mine.my_other_models.create!(attribute: 'Me') if mine
  end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM