RSpec测试没有调用控制器

时间:2011-07-15 07:01:53

标签: ruby-on-rails ruby-on-rails-3 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()不像这样调用控制器?

2 个答案:

答案 0 :(得分:8)

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

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