2023-10-09 03:13PM
单元测试文件:
# test/controllers/cars_controller_test.rb
require 'test_helper'
class CarsControllerTest < ActionDispatch::IntegrationTest
test "should get index" do
get cars_url
assert_response :success
end
end
在运行单元测试的时候一直报错说:Expected response to be a <2XX: success>, but was a <403: Forbidden>
$ bundle exec rails test test/controllers/cars_controller_test.rb
Run options: --seed 15315
# Running:
F
Failure:
CarsControllerTest#test_should_get_index [/home/meiyi/workspace/baogongpingtai-pc/test/controllers/cars_controller_test.rb:12]:
Expected response to be a <2XX: success>, but was a <403: Forbidden>
rails test test/controllers/cars_controller_test.rb:10
Finished in 0.161935s, 6.1753 runs/s, 6.1753 assertions/s.
1 runs, 1 assertions, 1 failures, 0 errors, 0 skips
解决方法:
1.在 config/application.rb 文件中,注释/删除任何 config.hosts << "your-hostname>"
# config.hosts << "xxxxxxxx.com"
# config.hosts << "www.xxxxxx.com"
我的 config/application.rb 文件中有两个 config.hosts << "your-hostname>"
,所以把他们都注释掉
2. 增加 test/fixtures/managers.yml
manager1:
email: admin@email.com
encrypted_password: xxxxxxxx
3. 打开 test/controllers/cars_controller_test.rb,修改代码:
require 'test_helper'
class CarsControllerTest < ActionDispatch::IntegrationTest
include Devise::Test::IntegrationHelpers
setup do
@manager = managers(:manager1)
sign_in @manager
end
test "should get index" do
get cars_url
assert_response :success
end
end
修改完上面几步,然后在重新运行单元测试
$ bundle exec rails test test/controllers/cars_controller_test.rb
Run options: --seed 9283
# Running:
.
Finished in 0.281973s, 3.5464 runs/s, 3.5464 assertions/s.
1 runs, 1 assertions, 0 failures, 0 errors, 0 skips
就发现已经可以了
登录
请登录后再发表评论。
评论列表:
目前还没有人发表评论