Joe Half Face
Joe Half Face

Reputation: 2333

How do I check both rendering :new and JSON response?

I try to add RSpec test for invalid entry create controller action, which responds to HTTP POST verb.

  it "case of invalid entry" do
      program=FactoryGirl.attributes_for(:program, :faculty_id => faculty.id, :code=>"воруй&убивай")
      post :create, {:program=>program, :faculty_shortcut=>faculty }
      expect(response).to render_template(:new)
    end

Controller:

 if @program.save
    redirect_to faculty_program_path(faculty, @program)
    else
      render :new,:json => @program.errors
    end

What I get from RSpec

Failure/Error: expect(response).to render_template(:new)
       expecting <"new"> but rendering with <[]>

Upvotes: 0

Views: 54

Answers (1)

BroiSatse
BroiSatse

Reputation: 44685

This means that the record has been saved and you have been redirected. If you want to check behaviour when invalid data is passed, do not rely on existing validations as they might change in the future. Just stub valid? method:

it "case of invalid entry" do
      program=FactoryGirl.attributes_for(:program)
      allow_any_instance_of(Program).to receive(:valid?).and_return false
      post :create, {:program=>program, :faculty_shortcut=>faculty }
      expect(response).to render_template(:new)
    end

Stubbing valid? has this advantage that your test will not change when you change your validations. Validations on their own should be tested within model tests, this way single change in the code won't cause multiple test fails.

Upvotes: 1

Related Questions