大家好,我完全迷失了这个。
我在网上找到了一个代码片段,以帮助在用户输入字段时通过 ajax 验证字段。因此,我正在尝试针对其中的一部分编写规范,但我无法让它通过。
这是代码
def validate
field = params[:field]
user = User.new(field => params[:value])
output = ""
user.valid?
if user.errors[field] != nil
if user.errors[field].class == String
output = "#{field.titleize} #{user.errors[field]}"
else
output = "#{field.titleize} #{user.errors[field].to_sentence}"
end
end
render :text => output
end
到目前为止,这是我的测试
describe "POST validate" do
it "retrieves the user based on the past in username" do
mock_errors ||= mock("errors")
mock_errors.stub!(:[]).and_return(nil)
User.should_receive(:new).with({'username'=>"UserName"}).and_return(mock_user)
mock_user.should_receive(:valid?).and_return(true)
mock_errors.should_receive(:[]).with("username").and_return(nil)
put :validate, :field=>'username', :value=>'UserName'
response.should == ""
end
end
我得到这个错误 -
1) Spec::Mocks::MockExpectationError in 'UsersController POST validate 根据用户名中的过去检索用户' Mock 'errors' 收到意外消息:[] with ("username")
我似乎无法弄清楚世界上如何模拟对 user.errors[field] 的调用。理想情况下,此规范测试快乐的路径,没有错误。然后我会为验证失败写另一个。