繁体   English   中英

如何测试Rails模型关联

[英]How to test Rails model associations

尝试测试模块。 它在Rails控制台中执行时有效,但在作为测试编写时则无效。 假设以下内容:

  1. 为MyModel

    a)has_many:my_other_model

  2. MyOtherModel

    a)属于:my_model

模块示例:

module MyModule

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

end

现在测试:

require 'test_helper'

class MyModuleTest < ActiveSupport::TestCase

  test "should work" do
    assert MyModule.doit
  end

end

返回:

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

现在,在控制台中尝试相同的操作:

rails c

MyModule.doit

效果很好。 但是为什么不做测试呢?

运行此测试时,测试数据库为空,因此调用MyModel.first将返回nil ,然后尝试将未知方法链接到nil。 您可能需要的测试套件是Fixture ,它只是示例数据。 现在,您只需创建第一个实例即可使测试生效。

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

您也可以重构模块。 如果我的不为零,则添加if mine将仅尝试创建其他模型。 那会使测试通过,但会否定测试的目的。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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