RSpec NoMethodError:未定义的方法`assign'

时间:2014-08-01 01:51:08

标签: ruby-on-rails gem rspec-rails nomethoderror

我正在尝试为我为Rails编写的小宝石编写测试。我想独立于虚拟应用程序测试宝石,觉得这对我来说是一个很好的学习经历。但是,由于上述错误,我无法通过简单的测试。

我的Gemfile指向gemspec,我用rspec --init初始化了RSpec。

我的测试(只是为了确保在我开始欧内斯特之前所有设置都正确):

RSpec.describe 'text_field', type: :view do
    it 'has something on the page' do
        assign(:users, [
          mock_model("User", id: 1, name: 'Ashley')
        ])
        stub_template 'users/_form.html.erb' => "<%= form_for @user do |f| %><%= f.text_field :name' %><% end %>"
        render
        rendered.should =~ /Ashley/
    end
end

整个错误:

text_field
  has something on the page (FAILED - 1)

Failures:

  1) text_field has something on the page
     Failure/Error: assign(:users, [
     NoMethodError:
       undefined method `assign' for #<RSpec::ExampleGroups::TextField:0x007faa143e8828>
     # ./spec/tests/text_field_spec.rb:4:in `block (2 levels) in <top (required)>'

Finished in 0.03812 seconds (files took 0.22166 seconds to load)
1 example, 1 failure

Failed examples:

rspec ./spec/tests/text_field_spec.rb:3 # text_field has something on the page

Top 1 slowest examples (0.03727 seconds, 97.8% of total time):
  text_field has something on the page
    0.03727 seconds ./spec/tests/text_field_spec.rb:3

我的gemspec:

  ...
  spec.test_files    = Dir["spec/**/*.rb"]

  spec.required_ruby_version = "2.1.2"
  spec.add_development_dependency "bundler", "1.6.3"
  spec.add_development_dependency "rails", "4.1.4"
  spec.add_development_dependency "rspec-rails", "3.0.1"
  spec.add_development_dependency "rspec-activemodel-mocks", "1.0.1"
  ...

我的spec_helper.rb:

require 'rspec/active_model/mocks'

RSpec.configure do |config|

  config.filter_run :focus
  config.run_all_when_everything_filtered = true

  if config.files_to_run.one?
    config.default_formatter = 'doc'
  end

  config.profile_examples = 10
  config.order = :random

  Kernel.srand config.seed

  config.expect_with :rspec do |expectations|
    expectations.syntax = :expect
  end

  config.mock_with :rspec do |mocks|
    mocks.syntax = :expect
    mocks.verify_partial_doubles = true
  end

end

我已将测试类型指定为视图,因为我对RSpec文档的理解是分配仅在视图中可用。我错过了某个重要的步骤,或者我错过了什么?

2 个答案:

答案 0 :(得分:4)

正如Jarl所说,答案是将type: view放在测试文件中的某个位置。

require 'spec_helper'

describe 'search/print/_asset.html.haml', type: :view do
  it 'displays the page' do
    asset = build(:asset)
    render 'search/print/asset', asset: asset
    assert_select ":match('href', ?)", "/asset/#{asset.property_id}"
  end
end

您可以更有选择性地放置它。这也有效:it 'displays the page', type: view do ... end

答案 1 :(得分:-1)

你有一个错字。您使用了assign,但应该使用assigns