是否可以在控制器中测试私有方法?这实际上决定了该记录是否应该保存在数据库中。
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
在创建方法测试期间,调用并测试私有方法is_valid_schedule
。如果您想单独测试此私有方法。看下面的例子:
class Admin::MembersController < Admin::BaseController
#some code
private
def is_valid_example
@member.new_record?
end
end
和test for private method:
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