【问题标题】:How to write specs for rails associations?如何为 Rails 协会编写规范?
【发布时间】:2011-11-18 21:43:19
【问题描述】:

他们说完美的测试只包括测试框架和被测试的类;其他一切都应该被嘲笑。那么,联想呢?

我指的不是简单的has_manybelongs_to 关联,而是关联扩展和范围。我真的很想为范围编写规范,但我就是不知道该怎么做。

【问题讨论】:

    标签: ruby-on-rails-3 rspec associations scopes


    【解决方案1】:

    我也对此感到困惑。在 Rspec 中,他们摆脱了“单元测试”的想法。在实践中,Rails 中的单元测试至少对我来说意味着测试模型上的属性值。但你是对的,联想呢?

    在 Rspec 中,您只需创建一个 spec/models 目录,然后测试您的模型。在模型规范 (spec/models/user_spec.rb) 的顶部,您进行了单元测试(测试您的属性),然后您在下面测试每个关联:

    require 'spec_helper'
    
    describe User do
      context ":name" do
        it "should have a first name"
        it "should have a last name"
      end
    
      # all tests related to the gender attribute
      context ":gender" do
        it "should validate gender"
      end
    
      # all tests related to "belongs_to :location"
      context ":location" do
        it "should :belong_to a location"
        it "should validate the location"
      end
    
      # all tests related to "has_many :posts"
      context ":posts" do
        it "should be able to create a post"
        it "should be able to create several posts"
        it "should be able to list most recent posts"
      end
    end
    

    但是现在您在User 测试中测试PostLocation 模型?是的。但是Post 模型除了与用户相关的功能之外,还有很多额外的东西。与Location 相同。所以你会有一个spec/models/location_spec.rb 喜欢:

    require 'spec_helper'
    
    describe Location do
      context ":city" do
        it "should have a valid city"
      end
    
      context ":geo" do
        it "should validate geo coordinates"
      end
    end
    

    在我看来,这些都不应该被嘲笑。在某些时候,您必须实际测试关联是否正在保存并且可查询。就在这里。想想看,在模型规范中,你有属性的“单元测试”和关联的“集成测试”。

    【讨论】:

    • 很好的解释,谢谢!我想补充一点,您应该另外有以下规则:测试您在模型中拥有的关联部分(用户 -> 评论 == 测试,从用户对象角度创建、获取、删除谁);不要说ActiveRecord 有效,只测试您对ActiveRecord 的使用是否有效。
    • 我会补充说“测试你自己编写的代码”。如果您的模型类对关联所做的唯一事情是定义它,那么确保定义关联就足够了(例如,通过确保您可以访问夹具上的 has_many 数组)。如果方法调用 has_many#build,请测试您的方法,而不是 has_many 的#build 功能。不要采取“我的模型保证属性posts可以做x、y、z,所以我必须测试它可以做x、y、z。那样是疯狂的。注意具体选项组合算作测试 imo 的“您的代码”
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多