我目前正在使用rspec编写集成测试。我遇到问题的测试是相当简单的:
accounts_controller.rb
def create
@account = Account.new(account_params)
authorize @account
if @account.save
flash[:notice] = 'Your account has been successfully created'
redirect_to :root
else
render :new
end
sign_up_spec.rb
require 'rails_helper'
feature 'Accounts' do
scenario 'creating an account' do
visit root_path
click_link 'Get Started'
fill_in 'Name', with: 'Test'
click_button 'Create account'
save_and_open_page
success_message = 'Your account has been successfully created'
expect(page).to have_content(success_message)
end
end
问题是,在开发过程中,注意到成功创建帐户的的Flash消息会出现,但是当我启动测试套件时,我从rspec那里得到一个错误,说它没有找到成功消息,实际上在使用save_and_open_page
之后,屏幕上没有任何内容......
测试日志
Started POST "/accounts" for 127.0.0.1 at 2017-05-04 18:27:20 +0200
Processing by AccountsController#create as HTML
Parameters: {"utf8"=>"✓", "account"=>{"name"=>"Test"}, "commit"=>"Create account"}
[1m[36m (0.1ms)[0m [1mSAVEPOINT active_record_1[0m
[1m[35mSQL (0.3ms)[0m INSERT INTO "accounts" ("name", "created_at", "updated_at") VALUES ($1, $2, $3) RETURNING "id" [["name", "Test"], ["created_at", "2017-05-04 16:27:20.224700"], ["updated_at", "2017-05-04 16:27:20.224700"]]
[1m[36m (0.1ms)[0m [1mRELEASE SAVEPOINT active_record_1[0m
Redirected to http://localhost/
Completed 302 Found in 6ms (ActiveRecord: 0.7ms)
Started GET "/" for 127.0.0.1 at 2017-05-04 18:27:20 +0200
Processing by PagesController#home as HTML
Rendered pages/home.html.erb within layouts/home (5.0ms)
Rendered shared/_navbar_home.html.erb (1.1ms)
Rendered shared/_flashes.html.erb (0.1ms)
Rendered shared/_footer.html.erb (0.6ms)
Completed 200 OK in 10ms (Views: 9.4ms | ActiveRecord: 0.0ms)
答案 0 :(得分:1)
最好的猜测是,您的初始visit root_path
正在使用'www.example.com'的rack_test驱动程序default_host。这意味着会话cookie(包含闪存)正在为'example.com'设置,因此当应用重定向到http://localhost
时不会发送,因为域不匹配。一种解决方案是从redirect_to :root
(最终调用url_for(:root)
确定目的地)更改为redirect_to root_path
,在重定向时只使用当前主机名。