Checking ActiveRecord Associations in RSpec

前端 未结 4 1386
长情又很酷
长情又很酷 2021-02-05 10:16

I am learning how to write test cases using Rspec. I have a simple Post Comments Scaffold where a Post can have many Comments. I am testing this using Rspec. How should i go abo

4条回答
  •  逝去的感伤
    2021-02-05 10:34

    Testing associations is good practice generally, especially in an environment where TDD is highly regarded- other developers will often look to your specs before looking at the corresponding code. Testing associations makes sure that your spec file most accurately reflects your code.

    Two ways you can test associations:

    1. With FactoryGirl:

      expect { FactoryGirl.create(:post).comments }.to_not raise_error
      

      This is a relatively superficial test that will, with a factory like:

      factory :post do
        title { "Top 10 Reasons why Antelope are Nosy Creatures" }
      end
      

      return you a NoMethodError if your model lacks a has_many association with comments.

    2. You can use the ActiveRecord #reflect_on_association method to take a more in-depth look at your association. For instance, with a more complex association:

      class Post
        has_many :comments, through: :user_comments, source: :commentary
      end
      

      You can take a deeper look into your association:

      reflection = Post.reflect_on_association(:comment)
      reflection.macro.should eq :has_many
      reflection.options[:through].should eq :user_comments
      reflection.options[:source].should eq :commentary
      

      and test on whatever options or conditions are relevant.

提交回复
热议问题