dimanche 12 juillet 2015

Ruby on Rails - How to Properly Test Models With Multiple Foreign Keys

So I'm writing unit tests for my rails application and a have a question about how to test a model that belongs_to two other different models. The model in question is for user generated reviews that are created by user and tied to a specific location within the application. Therefore, a single review belongs to both a location and a user. A single review has two foreign keys a location_id which ties the review to a location, and a author_id which ties a review to a user.

When I create a review inside my controller I have the user provide the location they want to create the review for and the user_id of the creator of the review. I then find the location and create the review like so:

@location = Location.find_by_id(params[:location_id])
@review = @location.reviews.new()
@review.review = params[:review]
@review.author_id = params[:author_id]
@review.save

Now both the location_id and author_id can't be null. The review field can't be null as well and has a validation within the model that checks to ensure that that the :presence =>true. The problem arises when I try to write a unit test to determine if that validation holds. Here is what I have so far:

test "should not save review without review text" do
    # Location created in the locations fixture
    location = Location.first
    location_review = location.reviews.new
    # User created in the users fixture
    location_review.author_id = User.first.id

    assert_not location_review.save, "Saved user without review text"
end

Here I create a review in exactly the same way I do within the the review controller I just stub out the location and author_id with data from my fixtures. Now the test runs and fails if I set a value to the review field as it should. However, something just feels wrong about the way I have done this. Should I not be creating a review from a location within a model test? Is that not correctly isolating the review model? Should I just create a new review and stub out the location_id and the author_id and not create one from a location? What is the proper way to test this model?

Aucun commentaire:

Enregistrer un commentaire