【问题标题】:Rails 3 + Rspec: Testing that a model has an attribute?Rails 3 + Rspec:测试模型是否具有属性?
【发布时间】:2013-12-28 15:53:38
【问题描述】:

有没有办法测试模型是否具有特定属性?现在我只是像这样使用respond_to

describe Category do
  it { should respond_to(:title) }
  ...
end

测试 Category 模型是否具有属性,但这仅测试是否存在名为 title 的实例方法。但是,我可以看到在某些情况下它们的行为是同义的。

【问题讨论】:

    标签: ruby-on-rails rspec


    【解决方案1】:

    您可以使用以下方法测试模型实例中是否存在属性:

    it "should include the :title attribute" do
      expect(subject.attributes).to include(:title)
    end
    

    或使用 its 方法(在 RSpec 3.0 的单独 gem 中):

    its(:attributes) { should include("title") }
    

    查看相关的How do you discover model attributes in Rails。 (感谢@Edmund 纠正its 示例。)

    【讨论】:

    • 这正是我想要的。谢谢!
    • @Edmund 你不知道我是多么尴尬/感谢你指出那个错误。我将参数保留为符号,因为它可以接受 字符串。
    • 没问题。不过,它对我来说不是一个符号。它必须是一个字符串。我认为这是因为它只是一个 ruby​​ 哈希,而不是 rails HashWithIndifferentAccess
    • 不,你也是对的。我对its 将符号而不是字符串作为参数的能力感到困惑。哎呀!已更正。
    • 即使值为 nil 也不返回true 吗?
    【解决方案2】:

    这有点像 necropost,但我写了一个自定义的 rspec 匹配器,它应该可以更容易地测试模型属性的存在:

    RSpec::Matchers.define :have_attribute do |attribute|
      chain :with_value do |value|
        @value = value
      end
    
      match do |model|
        r = model.attributes.include? attribute.to_s
        r &&= model.attributes[attribute] == @value if @value
        r
      end
    
      failure_message do |model|
        msg = "Expected #{model.inspect} to have attribute #{attribute}"
        msg += " with value #{@value}" if @value
        msg
      end
    
      failure_message_when_negated do |model|
        msg = "Expected #{model.inspect} to not have attribute #{attribute}"
        msg += " with value #{@value}" if @value
        msg
      end
    end
    

    【讨论】:

    【解决方案3】:

    如果你是这个意思,你可以测试这个类:

    @category.title.class.should eq String
    

    或者您可以定义一个测试实例,然后对其进行测试。

    @category = FactoryGirl.build(:category)
    @category.title.should eq <title from factory>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-28
      • 1970-01-01
      • 1970-01-01
      • 2011-11-24
      相关资源
      最近更新 更多