简体   繁体   中英

Rails 3 + Rspec: Testing that a model has an attribute?

Is there a way to test that a model has a specific attribute? Right now I am just using respond_to like this:

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

to test that the Category model has an attribute, but that only really tests that there is an instance method called title . However, I can see how in some situations they would behave synonymously.

You can test for the presence of an attribute in an instance of the model with the following:

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

or using the its method (in a separate gem as of RSpec 3.0):

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

See the related How do you discover model attributes in Rails . (Nod to @Edmund for correcting the its example.)

This is a bit of a necropost, but I wrote a custom rspec matcher that should make testing the presence of a model attribute easier:

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

You could test for the class, if that's what you mean:

@category.title.class.should eq String

or you could define a test instance and then test against that.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM