Forum: RSpec Why won't my simple controller spec pass?

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
Lee (Guest)
on 2009-05-15 10:50
(Received via mailing list)
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:

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

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.should_receive(:new).with("body" => "a quick brown
    post :create, :message => {"body" => "a quick brown fox"}

  it "should save the message"


Here is the controller:

class MessagesController < ApplicationController
  def create
    message = params[:message]

And here is the (mocked) model:

class Message


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
post :create, :context => {"name" => "fred"}

And then in the controller 'create' method: params[:context]

I did try this but received an error from my model and trace
suggesting that the "name" was not being supplied.

Lee (Guest)
on 2009-05-15 11:28
(Received via mailing list)
I have now managed to get the example to run as expected from The
RSpec Book.

I would appreciate pointers on the following though:

> post :create, :context => {"name" => "fred"}
> And then in the controller 'create' method:
> params[:context]
This topic is locked and can not be replied to.