[rspec-users] What is the best practices for controller specs?

Patrick J. Collins patrick at collinatorstudios.com
Fri Jun 28 14:21:10 UTC 2013


> Is it good to tests only if the controller render a template or redirect to
> another action?

My typical controller testing style is something like:

describe ArticleController do

  describe "#index" do
    it "renders the listing" do
      article = create(:article)
      get :index
      response.should be_success
      response.should_not be_redirect
      assigns[:articles].should == [article]
    end
  end

  describe "#show" do
    it "shows the record" do
      article = create(:article)
      get :show, :id => article.id
      response.should be_success
      response.should_not be_redirect
      assigns[:article].should == article
    end
  end

  describe "#create" do
    it "creates a record" do
      expect {
        post :create, :article => { :body => 'hot bod' }
      }.to change { Article.count }.by(1)
      response.should redirect_to articles_url
    end

    it "renders the new template on failure" do
      Article.any_instance.should_receive(:save).and_return(false)
      expect {
        post :create, :article => { :body => 'hot bod' }
      }.to_not change { Article.count }
      response.should_not be_redirect
      response.should render_template(:new)
      assigns[:article].should be_instance_of(Article)
      assigns[:article].should be_new_record
    end
  end

  # etc...

Patrick J. Collins
http://collinatorstudios.com


More information about the rspec-users mailing list