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 about checking for Post :has_many :comments
. Should I stub Post.comments
method and then check this with by returning a mock object of array of comment objects? Is testing for AR associations really required ?
Running tests by their file or directory names is the most familiar way to run tests with RSpec. RSpec can take a file name or directory name and run the file or the contents of the directory. So you can do: rspec spec/jobs to run the tests found in the jobs directory.
The currently accepted way to test rails controllers is by sending http requests to your application and writing assertions about the response. Rails has ActionDispatch::IntegrationTest which provides integration tests for Minitest which is the Ruby standard library testing framework.
rspec is a BDD test suite. Unlike Test::Unit, rspec isn't built into the language's Standard Library, which means if you want to use this tool, you'll need to install an external program (these programs are called ruby gems) to your application before you can start using it.
Since ActiveRecord associations should be well-tested by the Rails test suite (and they are), most people don't feel the need to make sure they work -- it's just assumed that they will.
If you want to make sure that your model is using those associations, that's something different, and you're not wrong for wanting to test that. I like to do this using the shoulda gem. It lets you do neat things like this:
describe Post do
it { should have_many(:comments).dependent(:destroy) }
end
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:
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With