我有一个Foo模型,其中:name 在创建时是必需的。
我正在写一个规范来测试验证
it 'should not create an invalid Foo' do
fill_in "Name", :with=>""
# an error message will be displayed when this button is clicked
click_button "Create Foo"
end
如何确认页面上显示错误消息?
我已经尝试过
page.errors.should have_key(:name)
,但这是不对的。我想我可以做
page.should have_content("Name can't be blank")
,但我宁愿避免将集成测试与内容如此紧密地结合在一起
最佳答案
如果要在单元测试级别正确地测试验证,则可以为所需的错误消息添加另一个测试很容易:
describe Foo do
describe "validations" do
describe "name" do
before { @foo = FactoryGirl.build(:foo) } # or Foo.new if you aren't using FactoryGirl
context "when blank" do
before { @foo.name = "" }
it "is invalid" do
@foo.should_not be_valid
end
it "adds the correct error message" do
@foo.valid?
@foo.errors.messages[:name].should include("Name cannot be blank")
end
end # positive test case omitted for brevity
end
end
end
这样,您已经隔离了错误生成并将其复制到模型,并且已经对其进行了可靠的测试,从而可以实现某种全局错误显示(例如,使用flash[:error],而不必在 View 中显式测试每个错误消息)等级。
关于ruby-on-rails - Rails和Rspec-表单提交失败时检查是否存在错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7841958/