I'm new to Rspec and I am trying to test my controller methods for basic functionality. I know I'm not supposed to test basic functionality, but I'm doing it more for learning purposes than to build something.
I have a controller called ProtocolsController. The controller is used for basic CRUD functionality. I am trying to test the controllers #create method. Below is my #create controller:
def create
@protocol = Protocol.new(protocol_params)
if @protocol.save
flash[:notice] = 'New protocol added'
redirect_back(fallback_location: 'test_results#index')
else
flash[:notice] = @protocol.errors[:name]
render 'new'
end
end
To test the sad path, I want to pass to the controller a mock object that contains the necessary parameters for creating an instance of the Protocol class. To do this I have the following code:
describe '#create' do
it 'fails to save because the name already exists' do
params = FactoryGirl.attributes_for(:protocol)
post :create, :protocol => params
end
end
Now I know the test is incomplete, but I am testing one line at a time and when I run Rspec I get the following error:
Failure/Error: post :create, :protocol => params
ArgumentError:
unknown keyword: protocol
But when I change post to: expect { post :create, :protocol => params }
It works. Which brings me to my questions:
- Why is the first post (
post :create, :protocol => params
) failing? - How would I go about sending a mock object to the controller?
- Why does the expect version work?
Any insight into the questions will be much appreciated. I've been scratching my head trying to figure this out and my guess is that it's an obvious answer.