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
Phrancis
20.5k6 gold badges69 silver badges155 bronze badges
asked Mar 13, 2012 at 9:25
\$\endgroup\$

1 Answer 1

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
answered Mar 24, 2012 at 8:38
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.