Rails 3 + Rspec:测试模型是否具有属性?

时间:2013-12-10 21:59:04

标签: ruby-on-rails rspec

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

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

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

3 个答案:

答案 0 :(得分:15)

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

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示例。)

答案 1 :(得分:1)

这是一个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

答案 2 :(得分:0)

如果这就是你的意思,你可以测试一下课程。

@category.title.class.should eq String

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

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