Search code examples
ruby-on-railsrspecruby-on-rails-4functional-testing

Testing Rails nested controllers


I have an Admin model which can manage Organizations. I have an AdminController with a simple index action and a child Admin::OrganizationsController controller which I'm trying to test.

The test for the canonical show action on this child controller passes without errors:

describe "GET show" do
  it "assigns the requested organization as @organization" do
    org = FactoryGirl.create(:organization)
    get :show, id: org.id # <---- this works
    expect(assigns(:organization)).to eq(org)
  end
end

but when I try to test the destroy action, I get an error I'm not able to understand (hence resolve):

describe "DELETE destroy" do
  it "destroys the requested organization" do
    org = FactoryGirl.create(:organization)
    delete :destroy, id: org.id # <---- (I tried to use org.id.to_param, unsuccessfully)
    # ...rest of the test
  end
end

with error:

Failure/Error: expect { delete :destroy, id: org.id }.to change(Organization, :count).by(-1)
     NameError:
       undefined local variable or method `organizations_url' for #<Admin::OrganizationsController:0x007fefe1622248>

I suspect this has to do with my controller being "nested" (it needs something like admin_organizations_url I guess).

Any help?

(additional side infos: Rails 4.0.1, rspec 3.0.0.beta1)


Solution

  • "Inspired" by CDub's comment, I took a look at the destroy action in Admin::OrganizationController, which looked like this:

    def destroy
      @organization.destroy
      respond_to do |format|
        format.html { redirect_to organizations_url } # <--- has to be admin_organizaions_url
        format.json { head :no_content }
      end
    end
    

    I didn't pay attention to the respond_to block at all.