在编写底层模型类之前编写控制器测试和类是否可能(并且合理)?我以为我看到了有关如何做到这一点的说明,但现在我找不到食谱了。
例如,考虑以下控制器:
# file: app/controllers/premises_controller.rb
class PremisesController < ApplicationController
def create
@premise = Premise.new(params[:premise])
respond_with @premise
end
end
我可以在创建基础前提模型和前提之前测试此控制器代码吗?我知道以下内容行不通——你将如何重写它(如果可能的话)?
# file: spec/controller/premise_spec.rb
require "spec_helper.rb"
describe PremisesController do
context 'POST create' do
it 'should assign a new Premise to @premise' do
premise = stub_model(Premise)
Premise.stub(:create) { premise }
post :create
assigns(:premise).should == premise
end
end
end
end
更新
我想得越多,我就越确信我确实需要定义这个Premise
类——PremisesController
代码需要引用它。所以我将把我的问题改为“是否有必要创建底层premises
数据库表才能运行PremisesController
测试?”
在这一点上,我没有看到解决它的好方法(不更改PremisesController
代码,这会破坏测试点)。例如,调用respond_with
调用@premise.has_errors?
依次访问数据库以获取列名。除非我愿意对内部方法存根ActiveRecord
,否则我看不到如何避免对数据库的影响。
但我很乐意以其他方式展示。