Question

I'm receiving the following error when trying to test with Draper:

NoMethodError: undefined method 'with_unit' for nil:NilClass

Here's 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's my decorator code:

class FoodDecorator < ApplicationDecorator
  decorates :food

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

My research suggests that the line ApplicationController.new.set_current_view_context should fix this, but it hasn't. Any thoughts?

Was it helpful?

Solution

replace with:

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 could 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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top