简体   繁体   English

如何在Rails Rspec中测试Api

[英]How to Test Api In Rails Rspec

I'm new to rails testing,i want to test my rails controller api. 我是Rails测试的新手,我想测试我的Rails Controller API。 I using gems rails-rspec , capybara and database-cleaner like this in my Gemfile: 我在我的Gemfile中使用了gems rails-rspeccapybaradatabase-cleaner

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

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

And in my spec folder i create a controller and create a user_controller_spec.rb inside my api folder and want to test create a user with valid parameters and write a code like this: 在我的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

But it gives me error : 但这给了我错误:

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

To be sure that your post query create an user you can write it like this: 为确保您的帖子查询创建了一个用户,您可以这样编写:

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

It test if a user is added to the database. 它测试是否将用户添加到数据库中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM