在编写控制器规格时,我可以用rspec获得一些反馈吗?

时间:2011-06-08 15:26:23

标签: ruby-on-rails model rspec rspec2

我想知道我是否可以通过控制器规格获得一些反馈。事实上,当我编写规格时,我是新手,而控制器的规格与模型的规格有所不同!所以我想知道我是否可能走错了方向......

subjects_controller.rb

def show
  @subject = Subject.find(params[:id])

  if @subject.trusted?(current_user)
    @messages = @subject.messages
  else
    @messages = @subject.messages.public
    @messages = @messages + @subject.messages.where(:user_ids => current_user.id)
    @messages.uniq!
  end

  # sort the list
  @messages = @messages.sort_by(&:created_at).reverse

  if !@subject.company.id == current_user.company.id
    redirect_to(subjects_path, :notice => "Invalid subject")
  end
end

subjects_controller_spec.rb

require 'spec_helper'

describe SubjectsController do  
  before(:each) do
    @subject = mock_model(Subject)
  end

  context "for signed users" do
    before(:each) do
      @current_user = sign_in Factory(:user)
    end

    context "GET #show" do
      before(:each) do
        Subject.stub!(:find, @subject).and_return(@subject)
      end

      context "when current_user is trusted" do
        before(:each) do
          messages = []
          company = mock_model(Company)

          @subject.should_receive(:trusted?).and_return(true)
          @subject.should_receive(:messages).and_return(messages)
          @subject.should_receive(:company).and_return(company)
        end

        it "should render success" do
          get :show, :id => @subject
          response.should be_success
        end
      end

      context "when current_user is not trusted" do
        before(:each) do
          messages = []
          company = mock_model(Company)

          @subject.should_receive(:trusted?).and_return(false)
          @subject.should_receive(:messages).and_return(messages)
          messages.should_receive(:public).and_return(messages)
          @subject.should_receive(:messages).and_return(messages)
          messages.should_receive(:where).and_return(messages)
          @subject.should_receive(:company).and_return(company)
        end

        it "should render success" do
          get :show, :id => @subject
          response.should be_success
        end
      end

      context "when subject's company is not equal to current_user's company" do
        # I have no idea of how to implement ==
      end
    end
  end
end

Factories.rb

Factory.define :user do |u|
  u.first_name 'Test User'                          #
  u.username 'Test User'                            #
  u.surname 'TheTest'                               #
  u.email 'foo@foobar.com'                          #
  u.password 'please'                               #
  u.confirmed_at Time.now                           #
end

2 个答案:

答案 0 :(得分:0)

据我所知,你走的是正确的道路。基本思想是在这些测试中将控制器代码与模型和视图完全隔离。您似乎正在这样做 - 存根和模拟模型交互。

答案 1 :(得分:0)

根本不要编写RSpec控制器规格。请改用黄瓜故事。更容易,你获得更好的报道。