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
./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.