[rspec-users] Why won't my simple controller spec pass?

Lee Lee.Longmore at googlemail.com
Fri May 15 03:16:21 EDT 2009


I have now managed to get the example to run as expected from The
RSpec Book.

I would appreciate pointers on the following though:

> As an aside, I already have an implemented model that I'd like to use
> in my controller spec. In this case, should I be using stub_model() to
> make use of it e.g.:
>
> context = stub_model(Context)
>
> Also the constructor expects a name to be passed in so can I write:
>
> Context.should_receive(:new).with("name" => "fred").and_return
> (message)
> post :create, :context => {"name" => "fred"}
>
> And then in the controller 'create' method:
>
> Context.new params[:context]



On 15 May, 07:28, Lee <Lee.Longm... at googlemail.com> wrote:
> I have been trying to spec a Rails Controller for the first time,
> having just completed my first View spec.
>
> Having hit a wall trying to spec a controller for my own application,
> I have tried to get an example in beta of The RSpec Book to work. I am
> however experiencing the same failures. I would appreciate any
> pointers on where I am going wrong.
>
> Here is the failure:
>
> 1)
> Spec::Mocks::MockExpectationError in 'MessagesController POST create
> should build a new message'
> <Message (class)> expected :new with ({"body"=>"a quick brown fox"})
> once, but received it 0 times
> ./spec/controllers/messages_controller_spec.rb:7:
> script/spec:10:
>
> Here is the controller spec:
>
> require File.expand_path(File.dirname(__FILE__) + '/../spec_helper')
>
> describe MessagesController, "POST create" do
>
>   it "should build a new message" do
>     message=mock_model(Message)
>     Message.should_receive(:new).with("body" => "a quick brown
> fox").and_return(message)
>     post :create, :message => {"body" => "a quick brown fox"}
>   end
>
>   it "should save the message"
>
> end
>
> Here is the controller:
>
> class MessagesController < ApplicationController
>   def create
>     message = Message.new params[:message]
>   end
> end
>
> And here is the (mocked) model:
>
> class Message
> end
>
> ***
>
> As an aside, I already have an implemented model that I'd like to use
> in my controller spec. In this case, should I be using stub_model() to
> make use of it e.g.:
>
> context = stub_model(Context)
>
> Also the constructor expects a name to be passed in so can I write:
>
> Context.should_receive(:new).with("name" => "fred").and_return
> (message)
> post :create, :context => {"name" => "fred"}
>
> And then in the controller 'create' method:
>
> Context.new params[:context]
>
> I did try this but received an error from my model and trace
> suggesting that the "name" was not being supplied.
>
> Thanks.
> _______________________________________________
> rspec-users mailing list
> rspec-us... at rubyforge.orghttp://rubyforge.org/mailman/listinfo/rspec-users


More information about the rspec-users mailing list