我有一个视图文件_edit.html.erb
<%= form_for(@search_phrase, remote: true) do |f| %>
<h4> Keyword </h4>
<%= f.text_field :keyword %><br/>
<%= f.submit "Add", class: "btn btn-medium btn-primary" %>
<%= render 'error' %>
<% end %>
我正在为它编写视图rspec测试/我的测试在_edit.html.erb_spec.rb中是这样的
describe "search_phrases/_edit.html.erb" do
include Devise::TestHelpers
User.destroy_all
before :all do
@user = User.find_by_name('testuser')
@user ||= begin
user = User.new(email: "test@gmail.com",
encrypted_password: "$2a$10$TIJrH0tmQ7VuDeBVBIYhJ......................",
provider: "facebook", uid: "10000697585", name: "testuser",
fb_token: "AUExuiUkFoBAEsYdxTfU1ONYanI55Sx5ThBTjo7qnKLiZ")
user.save!
user
end
end
before :each do
User.stub(:find_for_facebook_oauth).and_return(@user)
sign_in @user
end
before :all do
@search_phrase = SearchPhrase.find_by_user_id(@user.id)
@search_phrase ||= begin
search_phrase= SearchPhrase.new(keyword: "testkeyword",user_id: @user.id) #never hard code
search_phrase.save!
search_phrase
end
end
it "creates a form" do
render
rendered.should_receive(:form_for).with edit_search_phrase_path(@search_phrase)
end
end
但是测试没有给出错误
search_phrases/_edit.html.erb creates a form
Failure/Error: render
ActionView::Template::Error:
undefined local variable or method `search_phrase' for #<#<Class:0x000000073080c0>:0x00000007371b38>
# ./app/views/search_phrases/_edit.html.erb:1:in `_app_views_search_phrases__edit_html_erb__4315365547541336689_61378180'
# ./spec/views/search_phrases/_edit.html.erb_spec.rb:45:in `block (2 levels) in <top (required)>'
Finished in 0.30383 seconds
1 example, 1 failure
Failed examples:
rspec ./spec/views/search_phrases/_edit.html.erb_spec.rb:44 # search_phrases/_edit.html.erb creates a form
这里有什么问题,我无法弄明白。
答案 0 :(得分:0)
您可能错过了路线
#in routes.rb
resources :search_phrases
...
答案 1 :(得分:0)
您需要添加
assign(:search_phrase, @search_phrase)
在before :all
区块。即。
before :all do
@search_phrase = SearchPhrase.find_by_user_id(@user.id)
@search_phrase ||= begin
search_phrase= SearchPhrase.new(keyword: "testkeyword",user_id: @user.id) #never hard code
search_phrase.save!
search_phrase
end
assign(:search_phrase, @search_phrase
end
https://www.relishapp.com/rspec/rspec-rails/v/3-3/docs/view-specs/view-spec