【问题标题】:Rails - Testing JSON API with functional testsRails - 使用功能测试测试 JSON API
【发布时间】:2012-05-30 01:50:55
【问题描述】:

我只有一个简单的问题,但我找不到任何答案。

我的 ruby​​ on rails 3.2.2 应用程序有一个带有设计会话身份验证的 JSON API。

我的问题是:我如何通过功能或集成测试来测试这个 API - 有没有办法处理会话?

我没有前端,只有一个可以 GET 的 API。邮政。放。并使用 JSON 正文删除。

自动化测试的最佳方法是什么?

示例创建新用户

发布 www.exmaple.com/users

{
 "user":{
    "email" : "test@example.com",
    "password " : "mypass"
  }
}

【问题讨论】:

    标签: ruby-on-rails ruby unit-testing testing ruby-on-rails-3.1


    【解决方案1】:

    看看 Anthony Eden 的演讲 "Build and Test APIs with Ruby and Cucumber"

    【讨论】:

      【解决方案2】:

      您可以使用 Cucumber(BDD) 来测试这种情况,例如:

      Feature: Successful login
        In order to login
        As a user 
        I want to use my super API
      
        Scenario: List user
          Given the system knows about the following user:
            | email            | username |
            | test@example.com | blabla   |
          When the user requests POST /users
          Then the response should be JSON:
          """
          [
            {"email": "test@example.com", "username": "blabla"}
          ]
          """
      

      然后,您只需要编写您的步骤,pickle gem 会非常有用

      【讨论】:

        【解决方案3】:

        功能测试很容易做到。在用户示例中,我会将它们放在 Rspec 中的 spec/controllers/users_controller_spec.rb 中:

         require 'spec_helper'
        
         describe UsersController do
           render_views # if you have RABL views
        
           before do
             @user_attributes = { email: "test@example.com", password: "mypass" }
           end
        
           describe "POST to create" do
        
             it "should change the number of users" do
                lambda do
                  post :create, user: @user_attributes
                end.should change(User, :count).by(1)
             end
        
             it "should be successful" do
               post :create, user: @user_attributes
               response.should be_success
             end
        
             it "should set @user" do
               post :create, user: @user_attributes
               assigns(:user).email.should == @user_attributes[:email]
             end
        
             it "should return created user in json" do # depend on what you return in action
               post :create, user: @user_attributes
               body = JSON.parse(response.body)
               body["email"].should == @user_attributes[:email]
              end
          end
        

        显然,您可以优化上述规格,但这应该可以帮助您入门。干杯。

        【讨论】:

        • 你为什么推荐我使用 rspec?什么是rspec,rspec和普通测试有什么区别。
        • “正常测试”是什么意思?我只是喜欢 Rspec 方便的 DSL 和辅助方法的真实性。你目前在用什么?
        猜你喜欢
        • 1970-01-01
        • 2015-09-19
        • 1970-01-01
        • 2014-12-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多