3

尝试使用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应该可以解决这个问题,但事实并非如此。有什么想法吗?

4

1 回答 1

3

用。。。来代替:

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
于 2012-04-17T18:19:44.733 回答