1

我刚刚使用 Ruby 1.9.3-p0 升级到 Rails 3.2.1,我正在使用 Machinist 2.0。在更新一个大型项目之前,我的所有测试都通过了。我遇到的问题是,当我在 rspec 测试中的“让”调用中创建蓝图,然后在 before do 块中引用它时。

  let (:new_post) {Post.make!}

  before do
    Post.stub!(:new).and_return(new_post)
  end

这曾经有效,现在我收到以下错误:

  1) PostsController GET index assigns all posts as @posts
     Failure/Error: let (:new_post) {Post.make!}
     NoMethodError:
       undefined method `title=' for nil:NilClass
     # ./spec/support/blueprints.rb:22:in `block in <top (required)>'
     # ./spec/controllers/posts_controller_spec.rb:37:in `block (2 levels) in <top (required)>'
     # ./spec/controllers/posts_controller_spec.rb:40:in `block (2 levels) in <top (required)>'

这是我的蓝图:

require 'machinist/active_record'
Post.blueprint do
  title {"Post"}
  body {"hello world"}
end

现在我的工作是使用 before do 块中的实例变量来创建它们,但是使用“let”调用会很好,因为它可以让我的 rspec 测试更干净。

4

1 回答 1

0

Funny, I just ran across the exact same problem, although I'm on Rails 3.2.1, Machinist 2.0, and ruby 1.9.2-p290. I think there's a conflict between the execution of the Post.stub(:new) stub method and the Machinist make method, but I haven't dug into the code.

The best solution I've come up with is:

  before do
    new_post
    Post.stub!(:new).and_return(new_post)
  end

This will initialize the let (since let is lazy-loaded in rspec) before it gets to the stub method. It's hacky, but at least you (and I) can keep the let statement.

于 2012-02-21T12:04:10.747 回答