我有一个简单的测试,几乎是脚手架生成的,虽然我不明白为什么它不起作用。这里的情况:RSpec测试不调用控制器
我有一个AttachmentsController:
# POST /attachments
# POST /attachments.xml
def create
@attachment = Attachment.new(params[:attachment])
@attachment.idea_id = params[:idea_id]
respond_to do |format|
if @attachment.save
format.html { redirect_to(idea_path(params[:idea_id]), :notice => 'Attachment was successfully created.') }
format.xml { render :xml => @attachment, :status => :created, :location => @attachment }
else
format.html { render :action => "new" }
format.xml { render :xml => @attachment.errors, :status => :unprocessable_entity }
end
end
end
end
而一个规范:
describe AttachmentsController do
def mock_attachment(stubs={})
@mock_attachment ||= mock_model(Attachment, stubs).as_null_object
end
describe "POST create" do
describe "with valid params" do
it "assigns a newly created attachment as @attachment" do
Attachment.stub(:new).with({'these' => 'params'}) { mock_attachment(:save => true) }
post :create,:attachment => {'these' => 'params'}
assigns(:attachment).should be(mock_attachment)
end
但是这(在这个规范所有其他测试)失败,沿东西线
expected #<Attachment:33902000> => #<Attachment:0x2054db0 @name="Attachment_1001">
got #<NilClass:4> => nil
因为,我找不出原因,AttachmentsController#create是没有被调用。
路线有:
POST /attachments(.:format) {:action=>"create", :controller=>"attachments"}
这是日志说:
Processing by AttachmentsController#create as HTML
Parameters: {"attachment"=>{"these"=>"params"}}
Rendered text template (0.0ms)
Completed 302 Found in 52ms (Views: 23.1ms | ActiveRecord: 0.0ms)
我也应该注意到,我可以调用创建代码(和它的伟大工程),通过网站本身..这只是测试失败。
那么会导致post()或get()不能像这样调用控制器?
我不是很熟悉,但RSpec的是在我看来,'mock_attachment'是零可能你某事别的喜欢'替换它:TRUE'和运行测试? – Bohdan
你能发布完整的创建操作代码吗? – moritz
老兄你错过了创建代码。这是你问题的关键。 – lzap