Draper - NoMethodError with RSpec validation for decorator

When trying to test with Draper, I get the following error:

NoMethodError: undefined method 'with_unit' for nil:NilClass

Here is my test code:

# 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

And here is my decorator code:

class FoodDecorator < ApplicationDecorator
  decorates :food

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

My research shows that the string ApplicationController.new.set_current_view_contextshould fix this, but it is not. Any thoughts?

+3
source share
1 answer

replaced by:

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

You can even do:

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
+3
source

All Articles