dodgerogers747
dodgerogers747

Reputation: 3345

Rspec Tests fail using custom model validation

I have this custom validation method which makes sure you can't vote on your own content, and it causes quite a few RSpec test to fail with undefined method 'user_id' for nil:NilClass

Is there a way to rewrite the custom validation, or use a native rails validation?

failing tests
    12) Vote votable type 
         Failure/Error: @vote = FactoryGirl.create(:vote)
         NoMethodError:
           undefined method `user_id' for nil:NilClass
         # ./app/models/vote.rb:18:in `ensure_not_author'
         # ./spec/models/vote_spec.rb:5:in `block (2 levels) in <top (required)>'    
    validate :ensure_not_author

vote.rb

attr_accessible :value, :votable_id, :votable_type
  belongs_to :votable, polymorphic: true
  belongs_to :user

def ensure_not_author 
    votable = self.votable_type.downcase
    errors.add(:user_id, "You can't vote on your own content.") if self.votable.user_id == self.user_id
  end

if anyone needs more code just shout

Upvotes: 0

Views: 175

Answers (1)

plasticide
plasticide

Reputation: 1240

it looks like self.votable is nil. It appears as though this test should view the vote from the votable's point of view. If that's the case, then create the vote in the factory for your votable and move the test to your votable entity's suite, as you're really testing that the votable should not be able to vote on its own content.

Upvotes: 2

Related Questions