Ответ 1
В конце я только что использовал:
root_path
вместо:
root_url
Я следую RoR Tutorial, и я застрял в листинге 9.15
Я получаю следующую ошибку после запуска 'bundle exec rspec spec/':
1) Authentication authorization as wrong user submitting a PATCH request to the Users#update action
Failure/Error: specify { expect(response).to redirect_to(root_url) }
ArgumentError:
Missing host to link to! Please provide the :host parameter, set default_url_options[:host], or set :only_path to true
# ./spec/features/authentication_pages_spec.rb:79:in `block (5 levels) in <top (required)>'
Мой тестовый код проверки подлинности:
требуется "spec_helper"
describe "Authentication", type: :request do
subject { page }
describe "signin page" do
before { visit signin_path }
it { should have_content('Sign in') }
it { should have_title('Sign in') }
end
describe "signin" do
before { visit signin_path }
describe "with invalid information" do
before { click_button "Sign in" }
it { should have_title('Sign in') }
it { should have_selector('div.alert.alert-error', text: 'Invalid') }
describe "after visiting another page" do
before { click_link "Home" }
it { should_not have_selector('div.alert.alert-error') }
end
end
describe "with valid information" do
let(:user) { FactoryGirl.create(:user) }
before { sign_in user }
#it { should have_title(user.name) }
it { should have_link('Profile', href: user_path(user)) }
it { should have_link('Settings', href: edit_user_path(user)) }
it { should have_link('Sign out', href: signout_path) }
it { should_not have_link('Sign in', href: signin_path) }
describe "followed by signout" do
before { click_link "Sign out" }
it { should have_link('Sign in') }
end
end
end
describe "authorization" do
describe "for non-signed-in users" do
let(:user) { FactoryGirl.create(:user) }
describe "in the Users controller" do
describe "visiting the edit page" do
before { visit edit_user_path(user) }
it { should have_title('Sign in') }
end
describe "submitting to the update action" do
before { patch user_path(user) }
specify { expect(response).to redirect_to(signin_path) }
end
end
end
describe "as wrong user" do
let(:user) { FactoryGirl.create(:user) }
let(:wrong_user) { FactoryGirl.create(:user, email: "[email protected]") }
before { sign_in user, no_capybara: true }
describe "visiting Users#edit page" do
before { visit edit_user_path(wrong_user) }
#it { should_not have_title(full_title('Edit user')) }
end
describe "submitting a PATCH request to the Users#update action" do
before { patch user_path(wrong_user) }
specify { expect(response).to redirect_to(root_url) }
end
end
end
end
Я не знаю, как решить эту проблему, чтобы тест прошел. Как сделать Я разрешаю это? Может ли кто-нибудь объяснить, что пойдет не так? (Согласно учебнику, тест должен проходить).
В конце я только что использовал:
root_path
вместо:
root_url
Проблема может заключаться в том, что вы не определили default_host для тестовой среды. Определите default_host внутри config/environment/test.rb следующим образом:
config.action_mailer.default_url_options = {:host => "localhost:3000"}
Вы должны установить default_url в каждой среде (разработка, тестирование, производство).
Вам нужно внести эти изменения.
config/environments/development.rb
config.action_mailer.default_url_options =
{ :host => 'your-host-name' } #if it is local then 'localhost:3000'
config/environments/test.rb
config.action_mailer.default_url_options =
{ :host => 'your-host-name' } #if it is local then 'localhost:3000'
config/environments/development.rb
config.action_mailer.default_url_options =
{ :host => 'your-host-name' } #if it is local then 'localhost:3000'
Для тестов, таких как тесты контроллера, показанные в примере OP, для устранения этой ошибки необходим другой параметр. Упомянутый Kesha Antonov вместо этого вы можете использовать Routes default_url_options. Добавив следующий параметр в последней строке вашего config/environment/test.rb(после end), ваши тесты будут использовать хост для создания URL-адресов:
Rails.application.routes.default_url_options[:host] = 'lvh.me:3000'
Как упоминается OP в другом ответе, вместо этого вы можете переключиться на Path Named Route, когда ошибка связана с URL-адресом с именем route.
Если вы хотите установить предварительный просмотр по умолчанию для почтовых программ, вам понадобятся ссылки action_mailer.default_url_options в других ответах.
config.action_mailer.default_url_options = { :host => "localhost:3000" }
Подробнее об установке action_mailer см. в разделе Создание URL-адресов в Action Mailer API.
Вы можете избежать этой ошибки, используя метод skip_confirmation!.
user = User.new(email: "[email protected]", password: "1234pass5678word")
user.skip_confirmation!
user.save
user