如何重用多个控制器规范中使用的测试双精度数

时间:2011-12-28 06:56:21

标签: ruby-on-rails rspec2

我有一个使用AuthLogic的Rails应用程序,并且已经到了使用测试双打来介入current_user的程度。 current_user的状态集有限,在许多控制器规范中重复使用。

继续此示例,想象在每个上下文中具有类似双重设置的控制器。你可以看到很多重复的代码。为此应用一些DRY的首选方法是什么?

controller_1_spec.rb

require 'spec_helper'

describe Controller1 do

  describe "GET 'index'" do

    context "when user has state A" do
      before(:each) do
        user = double("User")
        user.stub(:state).and_return("A")
        user_session = double("UserSession")
        user_session.stub(:user).and_return(user)
        UserSession.stub(:find).and_return(user_session)
      end

      it "should test something for users with State A" do
        get :index
      end

      it "should test something else for users with State A" do
        get :index
      end
    end

    context "when user has state B" do
      before(:each) do
        user = double("User")
        user.stub(:state).and_return("B")
        user_session = double("UserSession")
        user_session.stub(:user).and_return(user)
        UserSession.stub(:find).and_return(user_session)
      end

      it "should test something for users with State B" do
        get :index
      end

      it "should test something else for users with State B" do
        get :index
      end
    end
  end
end

最好的方法是向spec_helper添加辅助方法,还是有更好的做法?

1 个答案:

答案 0 :(得分:1)

将设置代码移动到spec_helper.rb或spec / support / {something} .rb文件中定义的辅助方法。

def userInAStateWithSession
  user = double("User")
  user.stub(:state).and_return("A")
  user_session = double("UserSession")
  user_session.stub(:user).and_return(user)
  UserSession.stub(:find).and_return(user_session)
  return user
end

-

describe Controller1 do

  describe "GET 'index'" do

    context "when user has state A" do
      before(:each) do
        user = userInAStateWithSession
      end

      ...