ruby-on-rails - Rails和Rspec-表单提交失败时检查是否存在错误

标签 ruby-on-rails ruby-on-rails-3 rspec rspec2

我有一个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/

相关文章:

ruby-on-rails - Rails 状态 406 POST 响应

ruby - 来自 created_at 的不同天数的 ActiveRecord 计数?

ruby-on-rails - Rails 中的 Postgresql 准备语句:PG::Error: ERROR: 绑定(bind)消息提供 1 个参数,但准备语句 "a4"需要 0

sql - 如何显示 RSpec 测试生成的 SQL 查询日志?

ruby-on-rails - 如何修复Rails 5.1.7中的 `uninitialised constant ' ActiveRecord_Relation'`?

ruby-on-rails - 位 INVALID_URI - '500'

windows - JRuby on Rails 无法与在 Windows Server 2008 上作为服务运行的 Tomcat 一起使用

ruby-on-rails - rspec 中的别名 'it'

ruby-on-rails - RoR 中的关系表

ruby-on-rails - Rails 5,更新 Controller 中的特定表单字段