简体   繁体   中英

How to Test Api In Rails Rspec

I'm new to rails testing,i want to test my rails controller api. I using gems rails-rspec , capybara and database-cleaner like this in my Gemfile:

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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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