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 に答える