Rails RSpec测试无法正确通过

时间:2016-04-22 00:30:44

标签: ruby-on-rails ruby rspec

我正在使用RSpec为Cookbook模型编写模型测试。每个用户has_many食谱,每个食谱belongs_to一个用户。为了确保在没有用户的情况下无法创建Cookbook,我编写了以下测试:

it "is invalid without a user" do
  expect(FactoryGirl.build(:cookbook, user: nil)).to be_invalid
end

但是,在运行rspec时,我得到以下输出:

1) Cookbook is invalid without a user
   Failure/Error: expect(FactoryGirl.build(:cookbook, user: nil)).to be_invalid
   NoMethodError:
     undefined method `cookbooks' for nil:NilClass

那么,为了测试引发的错误,我做了这样的测试:

it "is invalid without a user" do
  expect{FactoryGirl.build(:cookbook, user: nil)}.to raise_error(NoMethodError)
end

但是,该测试也失败,输出如下:

1) Cookbook is invalid without a user
   Failure/Error: expect{FactoryGirl.build(:cookbook, user: nil)}.to raise_error(NoMethodError)
     expected NoMethodError but nothing was raised

如果有任何意义,这里是食谱的工厂:

require 'faker'

FactoryGirl.define do
  factory :cookbook do |f|
    f.title "#{Faker::Name.first_name}'s recipes"
    f.description "#{Faker::Name.last_name}'s favorite recipes."
    f.user 1
  end
end

我应该如何编写模型测试,以确保在创建Cookbook时需要用户?

1 个答案:

答案 0 :(得分:3)

在您的模型中,您可能需要进行一些验证,或者在回调之前调用用户模型上的var request = require('request'); var sinon = require('sinon'); describe('Job gets data', function(){ var server; beforeEach(function(){ server = sinon.fakeServer.create(); }); afterEach(function(){ server.restore(); }); context('When there is a GET request to /something', function(){ it('will throw an error if response format is invalid', sinon.test(function(done){ server.respondWith('GET', '/something', [200, { "Content-Type": "application/json" }, '{invalid: "data"}']); request.get('/something', function (err, response, body) { console.log(response); console.log(body); done(); }); })); }); 。当您在测试中调用bookshelves时,RSpec会在通过FactoryGirl构建的对象上调用be_invalid。该对象运行验证并引发错误,因为它尝试在valid?对象(用户)上调用bookshelves

当您测试错误提升时,不会发生这种情况,因为未在对象上调用nil。因此,如果您这样做,您的测试将引发错误:

valid?

但是,我不建议您仅对测试进行更改以使其通过。在调用it "is invalid without a user" do expect{FactoryGirl.build(:cookbook, user: nil).valid?}.to raise_error(NoMethodError) end 之前,您应该转到模型并检查用户是否在场。如果您不这样做,只要您尝试在没有用户的情况下创建bookshelves,您的应用就会中断。