2
\$\begingroup\$

I was just looking at a standard scaffolded Rails controller spec, and tried to get it to use subject or let blocks, and failed miserably ... can subject or let tidy controller specs the same as it would a model spec?

require 'spec_helper'

describe ProjectsController do

  def valid_attributes
    {}
  end

  def valid_session
    {}
  end

  before(:each) do
    @project = Project.create! valid_attributes
  end


  describe "GET index" do
    it "assigns all projects as @projects" do
      get :index, {}, valid_session
      assigns(:projects).should eq([@project])
    end
  end

  describe "GET show" do
    it "assigns the requested project as @project" do
      get :show, {:id => @project.to_param}, valid_session
      assigns(:project).should eq(@project)
    end
  end

  #etc
end
\$\endgroup\$
3
\$\begingroup\$

Check the answer from Pavel Druzyak for a different question. It answers your question as well.

Your code can be refactored to this;

describe ProjectsController do
    let(:project) { Project.create! }

    describe "GET index" do
      before(:each) { get :index }
      it { should respond_with(:success) }
      it { should assign_to(:projects).with([project]) }
    end

    describe "GET show" do
      before(:each) { get :show, {:id => @project.to_param} }
      it { should respond_with(:success) }
      it { should assign_to(:projects).with(project) }
    end
end
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.