2011-07-15 151 views
4

我有一个简单的测试,几乎是脚手架生成的,虽然我不明白为什么它不起作用。这里的情况: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()不能像这样调用控制器?

+0

我不是很熟悉,但RSpec的是在我看来,'mock_attachment'是零可能你某事别的喜欢'替换它:TRUE'和运行测试? – Bohdan

+0

你能发布完整的创建操作代码吗? – moritz

+0

老兄你错过了创建代码。这是你问题的关键。 – lzap

回答

3

你可以尝试should_receive,放入之前的块,因为它是一个更好的做法:

describe AttachmentsController do 
    describe "POST create" do 
    let(:attachment) { mock_attachment(:save => save_result) } 

    subject { post :create, :attachment => params } 

    before do 
     Attachment.should_receive(:new).and_return(attachment) 
    end 

    describe "with valid params" do 
     let(:attachment_params) { {'these' => 'params'} } 
     let(:save_result) { true } 

     it "assigns a newly created attachment as @attachment" do 
     assigns(:attachment).should be(mock_attachment) 
     end 
    end 
    end 
end 
+0

感谢您的建议,但即使有这样的做法我仍然有同样的问题 - 呼叫后:创造永不调用AttachemntController#创建 – lambinator

+10

啊,我只是看着日志...它重定向结束了 - 也许您必须先登录才能使用此操作?或者还有一些其他的过滤器可以实现重定向吗? – solnic

+0

哇,是的..就是这样。谢谢!! – lambinator

7

对于这个问题的未来观众,实际的答案被张贴@solnic到接受的答案评论: 检查您的日志。在这种情况下(以及在我自己的情况下),重定向导致了这个问题,这只能在日志中看到。