我是否需要在此测试中创建每个对象?

时间:2012-08-31 18:24:00

标签: ruby-on-rails ruby-on-rails-3 testing ruby-on-rails-3.2

我的测试看起来像这样:

def setup
    @period_registration= FactoryGirl.create(:period_registration)
  end


 test "should post save_period" do
    sign_in(FactoryGirl.create(:user))
     assert_difference('PeriodRegistration.count') do
      post :save_period, period_registration: FactoryGirl.attributes_for(:period_registration)
    end
    assert_not_nil assigns(:period_registration)

  end

但是当我运行它时,我收到了这个错误:

 1) Error:
test_should_post_save_period(PeriodRegistrationsControllerTest):
NoMethodError: undefined method `event' for nil:NilClass

这是我的控制器:

  def save_period
    @period_registration = PeriodRegistration.new(params[:registration])
    @period_registration.save
    flash[:success] = "Successfully Registered for Session."
    redirect_to event_url(@period_registration.period.event)
  end

我的工厂看起来像这样:

factory :event do
    name 'First Event'
    street '123 street'
    city 'Chicago'
    state 'Iowa'
    date Date.today
  end


  factory :period do
    name 'First Period'
    description 'This is a description'
    start_time Time.now + 10.days
    end_time Time.now + 10.days + 2.hours
    event
    product
  end

factory :period_registration do
    user
    period
  end

我是否需要创建句点对象和事件对象?如果是这样的话?我不认为这是问题所在,因为我相信通过" period"然后"产品"然后"事件"在各个工厂自动创建这些。

关于从这里看哪里的任何想法?

1 个答案:

答案 0 :(得分:1)

简短的回答 - 是的,你确实创造了对象。

答案很长:

  1. 在控制器中:

    @period_registration.period.event
    

    这行代码违反了The Law Of Demeter。这不是好设计。这行代码应如下所示:

    @period_registration.event
    

    但您必须在PeriodRegistration模型中创建新方法。最简单的方法变体可以是:

    def event
      period.event
    end
    
  2. 在控制器中:您不检查是否已保存PeriodRegistration模型。

  3. 据我所知,PeriodRegistration模型有2个关联,当您使用FactoryGirl.attributes_for时,工厂不会创建关联对象,它只会为PeriodRegistration提供一组属性。要使此测试通过,您应该为调用控制器创建这两个对象。最好的做法是 - 测试应该只有一个断言。例如:

    def setup
      @user = FactoryGirl.create(:user)
      @period = FactoryGirl.create(:period)
    end
    
    test "should post save_period" do
      sign_in(@user)
      assert_difference('PeriodRegistration.count') do
        post :save_period, period_registration: FactoryGirl.attributes_for(:period_registration, user: @user, period: @period)
      end
    end
    
    test "should assings @period_registration" do
      sign_in(@user)
      post :save_period, period_registration: FactoryGirl.attributes_for(:period_registration, user: @user, period: @period)
      assert_not_nil assigns(:period_registration)
    end
    
  4. 测试控制器时,您可以使用模拟对象而不是真实模型。