[英]Rails/Rspec integration tests with rspec and requests - route not matches for second test
我不明白为什么我的第二次测试不起作用。
这工作得很好:
require 'rails_helper'
require 'spec_helper'
RSpec.configure do |config|
config.include Devise::Test::IntegrationHelpers
end
RSpec.describe 'GET /users/:id', type: :request do
before(:all) do
@user = User.find_by(email: "user@dev.test")
sign_in @user
end
it "returns a user object" do
get "/users/#{@user.id}.json"
expect(response.status).to eq 200
expect(response).to have_http_status(:success)
expect(response.content_type).to eq("application/json; charset=utf-8")
expect(JSON.parse(response.body)["successful"]).to eql(true)
end
end
但是,如果我在同一个测试中添加第二个请求,如下所示:
require 'rails_helper'
require 'spec_helper'
RSpec.configure do |config|
config.include Devise::Test::IntegrationHelpers
end
RSpec.describe 'GET /users/:id', type: :request do
before(:all) do
@user = User.find_by(email: "user@dev.test")
sign_in @user
end
it "returns a user object" do
get "/users/#{@user.id}.json"
expect(response.status).to eq 200
expect(response).to have_http_status(:success)
expect(response.content_type).to eq("application/json; charset=utf-8")
expect(JSON.parse(response.body)["successful"]).to eql(true)
end
it "returns another user object" do
get "/users/#{@user.id}.json"
expect(response.status).to eq 200
expect(response).to have_http_status(:success)
expect(response.content_type).to eq("application/json; charset=utf-8")
expect(JSON.parse(response.body)["successful"]).to eql(true)
end
end
测试失败并出现错误:ActionController::RoutingError: No route matches [GET] "/users/2.json"
如您所见,两个测试都是相同的,但由于某种原因,第二个测试总是失败。
我认为这是因为测试环境中没有第二个用户。 像这样添加第二个用户
before(:all) do
@user_second = User.create(user_params)
...
end
但最佳实践是使用像 factory-bot 和“database-cleaner”这样的 gem。 也尝试使用'byebug'。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.