0

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

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.