ruby-on-rails - 发出请求之前规范中的 Rspec 2.7 访问 Controller session

标签 ruby-on-rails testing rspec rspec2

我正在使用 Rspec 测试我的 Controller ,在向路径发出请求之前,我似乎无法设置当前被测 Controller 的 session 变量。 例如,这有效:

  describe "GET /controller/path" do
    it "if not matching CRSF should display message" do
      get controller_path

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

这行不通(我收到一条错误消息,提示 session 不是 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

您也可以在 before(:each) block 中简单地使用 request.session[:user_id] = 123,但上面看起来更漂亮。

关于ruby-on-rails - 发出请求之前规范中的 Rspec 2.7 访问 Controller session ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8043956/

相关文章:

ruby - rspec 期望通过排除指定的键来比较两个散列

jquery - 从对话框窗口成功提交表单后,如何更新前端内容?

javascript - 如何在coffeescript中将两个jquery帖子合并为一个?

javascript - Ajax on Rails 如何使用 Ajax append 方法呈现 HTML?

testing - 本地、测试和生产版本控制

ruby-on-rails - Rails RSpec 测试 : Undefined method 'deliver' for nil:NilClass

ruby-on-rails - Rails 3.0 移动站点

firefox - 如何在 Selenium 测试中使用firefoxdriver上传文件

angular - 错误 : Cannot create the component ComponentClass as it was not imported into the testing module

ruby-on-rails - 设计 sign_in_and_redirect 导致 rspec 测试失败