I'm testing the create method on a controller for my Viewings model with RSpec. I am trying to create a mock viewing model to minimize calls to my database, stubbing out its new and save methods and returning the appropriate values to test whether the logic of my controller is working:
describe 'POST #create' do
let(:office_listing) { create(:office_listing) }
let(:viewing) { mock_model(Viewing).as_null_object }
····
before do·
Viewing.stub(:new).and_return(viewing)
end
describe 'with valid attributes' do
it 'saves the viewing' do·
Viewing.any_instance.stub(:save).and_return(true)
viewing.should_receive(:save)
post :create, office_listing_id: office_listing.id
end
end
describe 'with invalid attributes' do
it 'fails and renders a failure message' do
Viewing.any_instance.stub(:save).and_return(false)
viewing.should_receive(:save)
post :create, :office_listing_id => office_listing.id
assigns(:failure_message).should_not be_nil
end
end
end
end
here is my controller code:
def create
@viewing = Viewing.new(params[:viewing])
@viewing.broker = current_broker
@viewing.office_listing = params[:office_listing_id]
p @viewing.save
if @viewing && @viewing.save == true
respond_to do |format|
format.js
format.html { redirect_to root_path }
end
else
respond_to do |format|
@failure_message = "Unable to create viewing."
format.js
format.html { redirect_to root_path }
end
end
end
end
The problem is that, even though I have stubbed out save to return true or false depending on the test I am in, it always returns a viewing object, which leads me to believe that the stubbing isn't working and the controller is treating my mock object as a real object, making a database call when I call .save. Do I need to be using a class other than Viewing to stub out the method? Should I just be calling viewing.stub instead of Viewing.any_instance? Actually I think typing that may have answered my own question, but I'd still like to hear anyone's thoughts on the issue.