簡體   English   中英

如何在Rails Rspec中測試Api

[英]How to Test Api In Rails Rspec

我是Rails測試的新手,我想測試我的Rails Controller 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

在我的spec文件夾中,我創建一個控制器,並在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

為確保您的帖子查詢創建了一個用戶,您可以這樣編寫:

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

它測試是否將用戶添加到數據庫中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM