bte*_*les 4 ruby activerecord rspec
在rspec中创建ActiveRecord时,我使用fixture来获取有效记录.但是在测试中使用fxitures时,它们似乎无法通过验证.在以下示例中,员工似乎完全有效,但规范中的关联验证表明它们无效.
class Employee < ActiveRecord::Base
validates_presence_of :email
end
class User < ActiveRecord::Base
validates_associated :employee
end
#Command line debugger in 'debugger' (below) returns:
Employee.find(745185059).errors.count # => 0
Employee.find(745185059).errors.full_messages # => []
Employee.find(745185059).valid? # => true
Run Code Online (Sandbox Code Playgroud)
例如:
describe SessionsController do
fixtures :users, :employees
describe "Logging in by cookie" do
def set_remember_token token, time
@user[:remember_token] = token;
@user[:remember_token_expires_at] = time
debugger
@user.save! # THIS SAYS THE EMPLOYEE IS INVALID, but why, if the fixtures are good?
end
it 'logs in with cookie' do
stub!(:cookies).and_return({ :auth_token => 'hello!' })
logged_in?.should be_true
end
end
end
Run Code Online (Sandbox Code Playgroud)
为什么我得到验证失败的任何想法?(当然,我删除了很多中间代码,错误可能完全在其他地方)
您可以在.save(没有爆炸!)之后调试@user,它应该添加错误,它可能是由模型回调引起的,也可能是您的validate方法所做的事情.在你的测试中,只需:
@user.save
puts @user.errors.inspect # or your command line debugger
Run Code Online (Sandbox Code Playgroud)
并在运行测试时读取输出.
| 归档时间: |
|
| 查看次数: |
2069 次 |
| 最近记录: |