【问题标题】:Draper - NoMethodError with RSpec testing for decoratorDraper - NoMethodError 与 RSpec 测试装饰器
【发布时间】:2012-04-17 17:33:38
【问题描述】:

我在尝试使用 Draper 进行测试时收到以下错误:

NoMethodError: undefined method 'with_unit' for nil:NilClass

这是我的测试代码:

# spec/decorators/food_decorator_spec.rb
require 'spec_helper'

describe FoodDecorator do
  before { ApplicationController.new.set_current_view_context }
  FactoryGirl.create(:food)
  @food = FoodDecorator.first

  specify { @food.with_unit('water').should == "85.56 g" }
end

这是我的装饰器代码:

class FoodDecorator < ApplicationDecorator
  decorates :food

  def with_unit(nutrient)
    model.send(nutrient.to_sym).to_s + " g"
  end
end

我的研究表明,ApplicationController.new.set_current_view_context 行应该可以解决此问题,但事实并非如此。有什么想法吗?

【问题讨论】:

    标签: ruby-on-rails rspec draper


    【解决方案1】:

    替换为:

    require 'spec_helper'
    
    describe FoodDecorator do
      before do
        ApplicationController.new.set_current_view_context
        FactoryGirl.create(:food)
        @food = FoodDecorator.first
      end
    
      specify { @food.with_unit('water').should == "85.56 g" }
    end
    

    你甚至可以这样做:

    require 'spec_helper'
    
    describe FoodDecorator do
    
      let(:food) { Factory(:food) }
      subject { FoodDecorator.first }
    
      before do
        food
        ApplicationController.new.set_current_view_context
      end
    
      specify { subject.with_unit('water').should == "85.56 g" }
    end
    

    【讨论】:

    • 确实有效,但你能解释一下我哪里出错了吗?谢谢:)
    • 你的工厂没有包含在你的前块中,只是:)
    • 我在subject { FoodDecorator.first } 行的第二个代码块遇到问题,其中FactoryGirl.create 行尚未运行。我怀疑这是由于使用 let 语句进行记忆。由于工厂尚未运行,FoodDecorator.first 返回nil。删除 let 部分并将其保留为 FactoryGirl.create(:food) 可解决此问题。关于解决此问题的方法或我当前的解决方案是否可以接受的任何想法?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多