为什么装饰器会失败?
Why does decorator fail?
我的装饰器有问题:
class ReviewDecorator < Draper:Decorator
delegate_all
def author
@author = User.find_by(review.user_id)
"#{@author.firstname} #{@author.lastname}"
end
end
每次我测试这个装饰器时,我都会收到这个错误:
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:in
author'
# ./spec/decorators/review_decorator_spec.rb:10:in `block (3 levels) in '
Rspec 测试:
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
我做错了什么?
根据你的测试文件,代码应该是这样的。
class ReviewDecorator < Draper:Decorator
delegate_all
def author
"#{user.firstname} #{user.lastname}"
end
end
我的装饰器有问题:
class ReviewDecorator < Draper:Decorator
delegate_all
def author
@author = User.find_by(review.user_id)
"#{@author.firstname} #{@author.lastname}"
end
end
每次我测试这个装饰器时,我都会收到这个错误:
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:in
author' # ./spec/decorators/review_decorator_spec.rb:10:in `block (3 levels) in '
Rspec 测试:
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
我做错了什么?
根据你的测试文件,代码应该是这样的。
class ReviewDecorator < Draper:Decorator
delegate_all
def author
"#{user.firstname} #{user.lastname}"
end
end