How can I determine the subject of an rspec controller test?

房东的猫 提交于 2020-01-15 04:51:11

问题


So I don't have a great reason for needing to know this other than curiosity - the BEST reason - but I'm not sure what's going on here.

Background:
I'm working through the RSpec book and updating the examples.

On Chapter 24 - Rails Controllers there's a test for a messages controller.

## spec/controllers/messages_controller_spec.rb ##

require 'spec_helper'

describe MessagesController do
  describe "POST create" do
    let(:message) { mock_model(Message).as_null_object }

    before do
      Message.stub(:new).and_return(message)
    end

  # Then a bunch of Tests...

    context "when the message fails to save" do
      before do
        message.stub(:save).and_return(false)
        post :create
      end

      it "assigns @message" do
        assigns[:message].should eq(message)
      end

      it "renders the new template" do
        response.should render_template("new")
      end
    end
  end
end

This goes along with the messages controller:

## app/controllers/messages_controller.rb ##

class MessagesController < ApplicationController
  def create
    @message = Message.new(params[:message])

    if @message.save
      flash[:notice] = "The message was saved successfully"
      redirect_to action: "index"
    else
      render "new"
    end
  end
end



When I run the tests:

The test passes with response.

it "renders the new template" do
  response.should render_template("new")
end

The test also passes with subject.

it "renders the new template" do
  subject.should render_template("new")
end

The test Also passes with page

it "renders the new template" do
  page.should render_template("new")
end

The test ALSO passes with NOTHING

it "renders the new template" do
 should render_template("new")
end

In case it helps anyone make heads or tails of this, the config/routes.rb just has resources :messages

Why do all those tests pass? What am I actually testing? Are 'page', 'subject', and ' ' just synonyms for response? Does it matter as long as my tests pass?


回答1:


By default, the subject would be referencing the class, which is the MessagesController.

Not defining a subject in the last test example, will implicitly set the subject to be MessagesController.



来源:https://stackoverflow.com/questions/22027575/how-can-i-determine-the-subject-of-an-rspec-controller-test

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!