I’m writing a spec to test a down_vote method. But in order to test this I need to have an entry in the database for an existing vote. So my spec looks something like this:
describe "down_vote" do
it "lowers vote count" do
video = Factory.create(:video)
user = Factory.create(:user)
vote = Factory.vote(:vote, :voter_id => user.id, :voteable_id => video.id)
expect do
user.down_vote(video)
end.to change{ Vote.count }.by 1
end
end
Is it ok to write a spec/test like this? There seems to be a lot of setup which I’m not very comfortable with but I don’t really know any other way to test it.
Assuming that your spec works as intended, there’s nothing wrong with using factories inside individual test blocks as long as it doesn’t violate the DRY principle. If many tests are going to reference the same objects, then you may want to use RSpec let or before blocks to instantiate your factory objects.
You may also want to read the factory_girl documentation sections on “Using factories” and “Associations” to see if your particular tests can:
As a rule of thumb, it’s fine to perform test-specific setup inside the relevant test block. The important thing is to avoid repeatedly setting up the same data in a manual and error-prone way.