【问题标题】:How to Test Api In Rails Rspec如何在 Rails Rspec 中测试 Api
【发布时间】:2018-06-20 11:49:22
【问题描述】:

我是 Rails 测试新手,我想测试我的 Rails 控制器 API。 我在我的 Gemfile 中像这样使用 gems rails-rspeccapybaradatabase-cleaner

group :development, :test do
  gem 'rspec-rails', '~> 3.7'
end

group :test do
  gem 'database_cleaner'
  gem 'capybara'
end

在我的规范文件夹中,我创建了一个控制器并在我的 api 文件夹中创建了一个 user_controller_spec.rb 并想要测试创建一个具有有效参数的用户并编写如下代码:

RSpec.describe "API V1 Users", type: 'request' do
  describe "POST /api/v1/users" do
    context "with valid parameters" do
      let(:valid_params) do
        { 
          fname: "Riya",
          lname: "******",
          email: "*******.com",
          password: "",
          contact: "2144333",
          country_code:"91",
          address: "Sector 63",
          city: "Noida",
          state: "UP",
          country: "India",
          zipcode: "23001",
          role: "***",
          image: ""
        }
      end

  it "creates a new user" do
    expect { post "/api/v1/users", params: valid_params}
    expect(response).to have_http_status(:ok)  # it's use for code 200 
  end

  it "creates a user with the correct attributes" do
    post "/api/v1/users", params: valid_params 
    expect(User.last).to have_attributes valid_params
  end
end

context "with invalid parameters" do
   # testing for validation failures is just as important!
   # ...
end
  end
end

但它给了我错误:

Failure/Error: expect(User.last).to have_attributes valid_params expected nil to respond to :fname, :lname, :email, :password, :contact

【问题讨论】:

  • 请显示控制器操作和模型验证
  • 看起来您的参数无效并且用户未保存到数据库中
  • post "/api/v1/users", params: valid_params 您的帖子操作不会创建用户,这会导致 User.last 成为 nil 调试您的控制器操作。
  • 它创建一个用户并返回一个 id 为 1 的用户但是当我检查我的数据库时我没有看到该用户并且错误是 Error: expect(User.last).to have_attributes valid_params
  • 预期 # 具有属性 {:email => "xxx@xxx.com", :password => "123456", :fname => "Riya", :lname => "", :角色 => "", :...地址 => "xx", :city => "xx", :state => "x", :country => "x", :zipcode => "x", : image => ""} 但有属性 {:email => "xxx@xxx.com", :password => nil, :fname => "Riya", :lname => "Rajput", :role => "business ", :conta...dress => "Sector 63", :city => "Noida", :state => "UP", :country => "India", :zipcode => "23", :image = > 无}

标签: ruby-on-rails ruby testing rspec-rails


【解决方案1】:

为了确保您的帖子查询创建一个用户,您可以这样编写:

expect { post "/api/v1/users", params: valid_params}.to change(User, :count).by(1)

它测试是否将用户添加到数据库中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-06
    相关资源
    最近更新 更多