RSpec test does not call controller

I have a simple test, to a large extent, that created the scaffold, although I cannot understand why it does not work. Here's the situation:

I have an 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 

And specification:

 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 

but this (and every other test in this specification) fails with something in the lines

 expected #<Attachment:33902000> => #<Attachment:0x2054db0 @name="Attachment_1001"> got #<NilClass:4> => nil 

Because for reasons that I cannot understand, AttachmentsController # create is not called.

Route:

 POST /attachments(.:format) {:action=>"create", :controller=>"attachments"} 

Here is what the magazine says:

  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) 

I should also note that I can invoke the creation code (and it works fine) through the website itself .. these are just tests that fail.

So what can call post () or get () so as not to call such a controller?

+4
source share
2 answers

You can try should_receive and put it in a block before it gets better:

 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 
+3
source

For future viewers of this question, the actual answer was sent by @solnic in a comment on the accepted answer: check your magazines . In this case (and in my own situation) the redirect caused this problem, which was visible only in the logs.

+7
source

All Articles