mercredi 20 juin 2018

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

Aucun commentaire:

Enregistrer un commentaire