3

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?

Nick
  • 9,493
  • 8
  • 43
  • 66

1 Answers1

3

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
apneadiving
  • 114,565
  • 26
  • 219
  • 213
  • That did work, but can you explain where I went wrong? Thanks :) – Nick Apr 17 '12 at 18:29
  • 1
    your factory wasn't included in your before block, simply :) – apneadiving Apr 17 '12 at 18:30
  • I'm getting an issue with the second code block at the `subject { FoodDecorator.first }` line where the `FactoryGirl.create` line has not yet been run. I suspect this is due to memoizing with the `let` statement. Since the factory has not been run, `FoodDecorator.first` returns `nil`. Removing the `let` portion and leaving it only as `FactoryGirl.create(:food)` fixes this issue. Any thoughts on ways to solve this or if my current solution is acceptable? – Nick Apr 25 '12 at 19:40