Rspec控制器私有方法

时间:2013-01-11 05:45:55

标签: ruby-on-rails-3 rspec2

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

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

1 个答案:

答案 0 :(得分: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