Search code examples
ruby-on-railsdraper

Why does decorator fail?


I have problem with my decorator:

class ReviewDecorator < Draper:Decorator
  delegate_all

  def author
    @author = User.find_by(review.user_id)
    "#{@author.firstname} #{@author.lastname}"
  end
end

Every time I test this decorator, I receive this error:

ReviewDecorator#author displays review author fullname Failure/Error: expect(review.author).to eq 'John Doe' NoMethodError: undefined method firstname' for nil:NilClass # ./app/decorators/review_decorator.rb:7:inauthor' # ./spec/decorators/review_decorator_spec.rb:10:in `block (3 levels) in '

Rspec test:

require 'spec_helper'

describe ReviewDecorator do

  let(:user) { build(:user, firstname: 'John', lastname: 'Doe') }
  let(:review) { described_class.new(build(:review, user: user)) }

  describe '#author' do
    it 'displays review author fullname' do
      expect(review.author).to eq 'John Doe'
    end
  end
end

What I'm doing wrong?


Solution

  • According your test file, the code should be like this.

    class ReviewDecorator < Draper:Decorator
      delegate_all
    
      def author
        "#{user.firstname} #{user.lastname}"
      end
    end