1

是否可以在控制器中测试私有方法?这实质上决定了记录是否应该保存在数据库中。

def create
    logger.debug "inside CREATE"
    @schedule = Schedule.new(params[:schedule])

    if is_valid_schedule # <-- this is the private method
        if @schedule.save
            flash[:success] = "New schedule entry added!"
            redirect_to @schedule
        else
            render 'new'
        end
    else
        flash.now[:error] = "Schedule has an overlap"
        render 'new'
    end
end

我的测试如下所示:

describe "POST #create" do

        let!(:other_schedule) { FactoryGirl.create(:schedule) }

        before(:each) { get :new }

        describe "with valid attributes" do
            it "saves the new schedule in the database" do


                expect{ post :create, schedule: other_schedule }.to change(Schedule, :count).by(1)

            end

            it "redirects to the :show template" do
                post :create, schedule: other_schedule
                response.should redirect_to other_schedule
                flash[:success].should eq("New schedule entry added!")
            end
        end
4

1 回答 1

3

在您创建方法测试期间,is_valid_schedule调用并测试私有方法。如果你想单独测试这个私有方法。看下面的例子:

class Admin::MembersController < Admin::BaseController
  #some code
  private
   def is_valid_example
     @member.new_record?
   end
end

并测试私有方法:

require 'spec_helper'
describe Admin::MembersController do
 .... 
 #some code
  describe "test private method" do
   it "should be valid" do
     member = FactoryGirl.create(:member)
     controller.instance_variable_set('@member', member)
     controller.send(:is_valid_example).should be(false)
   end
  end
end
于 2013-01-11T07:24:12.923 回答