我发现了一个在线代码片段,可以帮助用户在输入时通过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 在'UsersController POST验证 根据过去检索用户 收到用户名'模拟'错误' 意外消息:[]用 ( “用户名”)
我似乎无法弄清楚如何模拟对user.errors [field]的调用。理想情况下,此规范测试快乐路径,没有错误。然后我会写另一个验证失败。
答案 0 :(得分:1)
我没有看到mock_user。这是一个镜头:
describe "POST validate" do
it "retrieves the user based on the past in username" do
mock_errors = mock("errors")
mock_user = mock("user")
mock_user.stub!(:errors).and_return([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(ActiveRecord::Errors.new({}))
put :validate, :field=>'username', :value=>'UserName'
response.should == ""
end
end
关键是你需要你的User mock通过返回空哈希或fieldname / errors的哈希来响应errors方法。另一种方法是使用夹具更换工具之一。我现在正在使用机械师,这可能会减少这一切:
describe "POST validate" do
it "retrieves the user based on the past in username" do
@user = User.make{'username'=>"UserName"}
@user.should_receive(:valid?).and_return(true)
@user.errors.should_receive(:[]).with("username").and_return(ActiveRecord::Errors.new({}))
put :validate, :field=>'username', :value=>'UserName'
response.should == ""
end
end