【问题标题】:Why does decorator fail?为什么装饰器会失败?
【发布时间】:2015-04-19 11:55:45
【问题描述】:

我的装饰器有问题:

class ReviewDecorator < Draper:Decorator
  delegate_all

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

每次我测试这个装饰器时,我都会收到这个错误:

ReviewDecorator#author 显示评论作者全名 失败/错误:expect(review.author).to eq 'John Doe' 无方法错误: 未定义的方法firstname' for nil:NilClass # ./app/decorators/review_decorator.rb:7:inauthor' # ./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

我做错了什么?

【问题讨论】:

  • 您也可以发布规范的相关部分吗?在调用此测试之前,您是否对作者进行了存根,或者测试数据库中是否有作者?
  • 我编辑了我的主要帖子并添加了 rspec。

标签: ruby-on-rails draper


【解决方案1】:

根据你的测试文件,代码应该是这样的。

class ReviewDecorator < Draper:Decorator
  delegate_all

  def author
    "#{user.firstname} #{user.lastname}"
  end
end

【讨论】:

    猜你喜欢
    • 2018-09-12
    • 2018-02-08
    • 1970-01-01
    • 2021-05-10
    • 1970-01-01
    • 2017-04-02
    • 2015-08-23
    • 1970-01-01
    • 2023-04-06
    相关资源
    最近更新 更多