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