Anderson Leite
2010-Jul-29 13:37 UTC
[rspec-users] Testing controller and action with parameters
I have an action and I am testing it like this: The action: ========= def create @event = Evento.new(params[:event]) @event.aproved = false if @event.save redirect_to :action => "index" else render :action => "new" end end The RSpec test: ============= before do @event = mock_model(Event) Event.stub!(:new).and_return(@event) @event.stub!(:aproved=).and_return(false) @event.stub!(:save).and_return(true) end it "should register some event and keep it not aproved" do Event.should_receive(:new).once @event.should_receive(:aproved=).once @event.should_receive(:save).once get "create" response.should redirect_to :action => ''index'' end It seems to be working for me and the test is passing, by I think this test is still ugly or probabily can be improved. How do you make tests like this? -- Posted via http://www.ruby-forum.com/.
David Chelimsky
2010-Jul-29 14:06 UTC
[rspec-users] Testing controller and action with parameters
On Jul 29, 2010, at 8:37 AM, Anderson Leite wrote:> I have an action and I am testing it like this: > > The action: > =========> def create > @event = Evento.new(params[:event]) > @event.aproved = false > if @event.save > redirect_to :action => "index" > else > render :action => "new" > end > end > > > The RSpec test: > =============> > before do > @event = mock_model(Event) > Event.stub!(:new).and_return(@event)Use stub instead of stub! (which will eventually be deprecated)> @event.stub!(:aproved=).and_return(false) > @event.stub!(:save).and_return(true)You can add the method stubs to the mock_model declaration: @event = mock_model(Event, :approved= => false, :save => true)> end > > it "should register some event and keep it not aproved" doThe word "and" in an example''s name suggests too many things are being spec''d in one example. I''d split these out into "registers the event" and "leaves the event un-approved" HTH, David> Event.should_receive(:new).once > @event.should_receive(:aproved=).once > @event.should_receive(:save).once > get "create" > response.should redirect_to :action => ''index'' > end > > > It seems to be working for me and the test is passing, by I think this > test is still ugly or probabily can be improved. > > How do you make tests like this?