之前项目时间紧迫,没有同步编写自测用例,现在项目从sqlserver迁移到postgreSQL,正好把测试用例补上,同时也学习下rails的自测,嗯,先从rails自带的测试框架搞起吧。先将自己常遇到的错误记录于下:
错误1(ERROR: relation "tasks" does not exist):
执行ruby unit\article_test.rb出现如下错误:
testtt_users_url(ActionController::TestCase):
ActiveRecord::StatementInvalid: PG::Error: ERROR: relation "tasks" does not exist
LINE 1: DELETE FROM "tasks"
^
: DELETE FROM "tasks"
分析:
由于之前用rails g model创建了task模型,在test\fixtures下添加了tasks.yml,但是后来的迁移干掉了task模型,对应的fixture却没有干掉。
Rails by default automatically loads all fixtures from the test/fixtures folder for your unit and functional test. Loading involves three steps:
Remove any existing data from the table corresponding to the fixture
Load the fixture data into the table
Dump the fixture data into a variable in case you want to access it directly
所以在加载的时候看到tasks.yml会首先DELETE FROM "tasks",所以error...
解决:
rm -f test/fixtures/tasks.yml
错误2(RuntimeError: Missing host to link to! ):
执行ruby unit\article_test.rb出现如下错误:RuntimeError: Missing host to link to!
Please provide :host parameter or set default_url_options[:host]
分析:
(sorry,等着回家,还没搞清楚,回来再看)
解决:
在网上寻找了下,常见有如下4种解决方法(但是只有方法D对我执行unit test有效,%>_<% ):
方法A:
在environments/#{Rails.env}.rb中添加如下代码(参考http://stackoverflow.com/questions/7219732/missing-host-to-link-to-please-provide-host-parameter-or-set-default-url-optio):
config.action_mailer.default_url_options = { :host => "www.yourhost.com" }
方法B:
在application_controller.rb中添加如下代码(参考http://stackoverflow.com/questions/6638949/missing-host-to-link-to-for-devise):
# application_controller.rb
before_filter :mailer_set_url_options
def mailer_set_url_options
ActionMailer::Base.default_url_options[:host] = request.host_with_port
end
方法C:
在application_controller.rb中添加如下代码(参考http://guides.rubyonrails.org/action_controller_overview.html#default_url_options):
class ApplicationController < ActionController::Base
def default_url_options
{:locale => I18n.locale}
end
end
方法D:
在config/routes.rb中添加如下代码(参考http://stackoverflow.com/questions/7219732/missing-host-to-link-to-please-provide-host-parameter-or-set-default-url-optio):
Your::Application.routes.draw do
default_url_options :host => "www.yourhost.com"
end
hanpp@glodon.com