ruby-on-rails – Rspec 2.7访问控制器会话在规格要求之前

前端之家收集整理的这篇文章主要介绍了ruby-on-rails – Rspec 2.7访问控制器会话在规格要求之前前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在使用Rspec来测试我的控制器,在向路径发出请求之前,我似乎无法设置当前控制器的会话变量.
例如这样做:
describe "GET /controller/path" do
    it "if not matching CRSF should display message" do
      get controller_path

      request.session[:state] = "12334"
    end
  end

这不工作(我得到一个错误,说会话不是一个Nil类的方法):

describe "GET /controller/path" do
        it "if not matching CRSF should display message" do
          request.session[:state] = "12334"
          get controller_path
        end
      end

有任何想法吗?

解决方法

使用新版本的RSpec,这样做相当不错,看看:
describe SessionController do
  # routes are mapped as:
  # match 'login' => 'session#create'
  # get 'logout' => 'session#destroy'

  describe "#create" do
    context "with valid credentials" do
      let :credentials do
        { :email => 'example@gmail.com',:password => 'secret' }
      end

      let :user do
        FactoryGirl.create(:user,credentials)
      end

      before :each do
        post '/login',credentials
      end

      it "creates a user session" do
        session[:user_id].should == user.id
      end
    end

    # ...
  end

  describe "#destroy" do
    context "when user logged in" do
      before :each do
        get "/logout",{},{ :user_id => 123 } # the first hash is params,second is session
      end

      it "destroys user session" do
        session[:user_id].should be_nil
      end

      # ...
    end
  end
end

你也可以使用简单的request.session [:user_id] = 123里面的(每个)块,但上面看起来更好.

原文链接:https://www.f2er.com/ruby/265710.html

猜你在找的Ruby相关文章